--- a/browser/base/content/browser-sidebar.js
+++ b/browser/base/content/browser-sidebar.js
@@ -171,19 +171,18 @@ var SidebarUI = {
*
* @param {string} commandID ID of the xul:broadcaster element to use.
* @return {Promise}
*/
toggle(commandID = this.currentID) {
if (this.isOpen && commandID == this.currentID) {
this.hide();
return Promise.resolve();
- } else {
- return this.show(commandID);
}
+ return this.show(commandID);
},
/**
* Show the sidebar, using the parameters from the specified broadcaster.
* @see SidebarUI note.
*
* @param {string} commandID ID of the xul:broadcaster element to use.
*/
--- a/browser/base/content/content.js
+++ b/browser/base/content/content.js
@@ -838,20 +838,20 @@ addMessageListener("ContextMenu:SearchFi
node.form.enctype == ""));
let title = node.ownerDocument.title;
let description = PlacesUIUtils.getDescriptionFromDocument(node.ownerDocument);
let formData = [];
function escapeNameValuePair(aName, aValue, aIsFormUrlEncoded) {
- if (aIsFormUrlEncoded)
+ if (aIsFormUrlEncoded) {
return escape(aName + "=" + aValue);
- else
- return escape(aName) + "=" + escape(aValue);
+ }
+ return escape(aName) + "=" + escape(aValue);
}
for (let el of node.form.elements) {
if (!el.type) // happens with fieldsets
continue;
if (el == node) {
formData.push((isURLEncoded) ? escapeNameValuePair(el.name, "%s", true) :
--- a/browser/base/content/pageinfo/pageInfo.js
+++ b/browser/base/content/pageinfo/pageInfo.js
@@ -183,20 +183,19 @@ gImageView.getCellProperties = function(
return props;
};
gImageView.getCellText = function(row, column) {
var value = this.data[row][column.index];
if (column.index == COL_IMAGE_SIZE) {
if (value == -1) {
return gStrings.unknown;
- } else {
- var kbSize = Number(Math.round(value / 1024 * 100) / 100);
- return gBundle.getFormattedString("mediaFileSize", [kbSize]);
}
+ var kbSize = Number(Math.round(value / 1024 * 100) / 100);
+ return gBundle.getFormattedString("mediaFileSize", [kbSize]);
}
return value || "";
};
gImageView.onPageMediaSort = function(columnname) {
var tree = document.getElementById(this.treeid);
var treecol = tree.columns.getNamedColumn(columnname);
--- a/browser/base/content/pageinfo/security.js
+++ b/browser/base/content/pageinfo/security.js
@@ -91,30 +91,28 @@ var security = {
retval.version = "TLS 1.2"
break;
case nsISSLStatus.TLS_VERSION_1_3:
retval.version = "TLS 1.3"
break;
}
return retval;
- } else {
- return {
- hostName : hostName,
- cAName : "",
- encryptionAlgorithm : "",
- encryptionStrength : 0,
- version: "",
- isBroken : isBroken,
- isMixed : isMixed,
- isEV : isEV,
- cert : null
-
- };
}
+ return {
+ hostName : hostName,
+ cAName : "",
+ encryptionAlgorithm : "",
+ encryptionStrength : 0,
+ version: "",
+ isBroken : isBroken,
+ isMixed : isMixed,
+ isEV : isEV,
+ cert : null
+ };
},
// Find the secureBrowserUI object (if present)
_getSecurityUI : function() {
if (window.opener.gBrowser)
return window.opener.gBrowser.securityUI;
return null;
},
@@ -173,19 +171,17 @@ var security = {
function securityOnLoad(uri, windowInfo) {
security.init(uri, windowInfo);
var info = security._getSecurityInfo();
if (!info) {
document.getElementById("securityTab").hidden = true;
return;
}
- else {
- document.getElementById("securityTab").hidden = false;
- }
+ document.getElementById("securityTab").hidden = false;
const pageInfoBundle = document.getElementById("pageinfobundle");
/* Set Identity section text */
setText("security-identity-domain-value", info.hostName);
var owner, verifier;
if (info.cert && !info.isBroken) {
--- a/browser/base/content/safeMode.js
+++ b/browser/base/content/safeMode.js
@@ -39,35 +39,33 @@ function showResetDialog() {
function onDefaultButton() {
if (defaultToReset) {
// Restart to reset the profile.
resetProfile();
restartApp();
// Return false to prevent starting into safe mode while restarting.
return false;
- } else {
- // Continue in safe mode. No restart needed.
- return true;
}
+ // Continue in safe mode. No restart needed.
+ return true;
}
function onCancel() {
appStartup.quit(appStartup.eForceQuit);
}
function onExtra1() {
if (defaultToReset) {
// Continue in safe mode
window.close();
return true;
- } else {
- // The reset dialog will handle starting the reset process if the user confirms.
- showResetDialog();
}
+ // The reset dialog will handle starting the reset process if the user confirms.
+ showResetDialog();
return false;
}
function onLoad() {
let dialog = document.documentElement;
if (appStartup.automaticSafeModeNecessary) {
document.getElementById("autoSafeMode").hidden = false;
document.getElementById("safeMode").hidden = true;
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -3886,19 +3886,18 @@
}
return true;
},
tinfo: function(tab) {
if (tab) {
return tab._tPos + "(" + tab.linkedBrowser.currentURI.spec + ")";
- } else {
- return "null";
}
+ return "null";
},
log: function(s) {
if (!this.logging())
return;
if (this._useDumpForLogging) {
dump(s + "\n");
} else {
--- a/browser/components/customizableui/CustomizableUI.jsm
+++ b/browser/components/customizableui/CustomizableUI.jsm
@@ -268,24 +268,22 @@ var CustomizableUIInternal = {
type: CustomizableUI.TYPE_TOOLBAR,
defaultPlacements: [
"menubar-items",
],
get defaultCollapsed() {
if (AppConstants.MENUBAR_CAN_AUTOHIDE) {
if (AppConstants.platform == "linux") {
return true;
- } else {
- // This is duplicated logic from /browser/base/jar.mn
- // for win6BrowserOverlay.xul.
- return AppConstants.isPlatformAndVersionAtLeast("win", 6);
}
- } else {
- return false;
+ // This is duplicated logic from /browser/base/jar.mn
+ // for win6BrowserOverlay.xul.
+ return AppConstants.isPlatformAndVersionAtLeast("win", 6);
}
+ return false;
}
}, true);
}
this.registerArea(CustomizableUI.AREA_TABSTRIP, {
legacy: true,
type: CustomizableUI.TYPE_TOOLBAR,
defaultPlacements: [
--- a/browser/components/extensions/ext-bookmarks.js
+++ b/browser/components/extensions/ext-bookmarks.js
@@ -48,20 +48,19 @@ function getTree(rootGuid, onlyChildren)
}
return item.annos &&
item.annos.find(a => a.name == PlacesUtils.EXCLUDE_FROM_BACKUP_ANNO);
},
}).then(root => {
if (onlyChildren) {
let children = root.children || [];
return children.map(child => convert(child, root));
- } else {
- // It seems like the array always just contains the root node.
- return [convert(root, null)];
}
+ // It seems like the array always just contains the root node.
+ return [convert(root, null)];
}).catch(e => Promise.reject({message: e.message}));
}
function convert(result) {
let node = {
id: result.guid,
title: result.title || "",
index: result.index,
--- a/browser/components/extensions/ext-browserAction.js
+++ b/browser/components/extensions/ext-browserAction.js
@@ -219,19 +219,18 @@ BrowserAction.prototype = {
this.updateOnChange(tab);
},
// tab is allowed to be null.
// prop should be one of "title", "badgeText", "popup", or "badgeBackgroundColor".
getProperty(tab, prop) {
if (tab == null) {
return this.defaults[prop];
- } else {
- return this.tabContext.get(tab)[prop];
}
+ return this.tabContext.get(tab)[prop];
},
shutdown() {
this.tabContext.shutdown();
CustomizableUI.destroyWidget(this.id);
},
};
--- a/browser/components/places/content/places.js
+++ b/browser/components/places/content/places.js
@@ -1029,19 +1029,18 @@ var ViewMenu = {
"endElement is not in popup");
NS_ASSERT(endElement,
"endID does not correspond to an existing element");
}
while (startElement.nextSibling != endElement)
popup.removeChild(startElement.nextSibling);
return endElement;
}
- else {
- while(popup.hasChildNodes())
- popup.removeChild(popup.firstChild);
+ while (popup.hasChildNodes()) {
+ popup.removeChild(popup.firstChild);
}
return null;
},
/**
* Fills a menupopup with a list of columns
* @param event
* The popupshowing event that invoked this function.
--- a/browser/components/places/tests/browser/browser_views_liveupdate.js
+++ b/browser/components/places/tests/browser/browser_views_liveupdate.js
@@ -261,21 +261,20 @@ var bookmarksObserver = {
var sidebar = document.getElementById("sidebar");
var tree = sidebar.contentDocument.getElementById("bookmarks-view");
let cellText = tree.view.getCellText(aElementOrTreeIndex,
tree.columns.getColumnAt(0));
if (!aNewValue)
return cellText == PlacesUIUtils.getBestTitle(tree.view.nodeForTreeIndex(aElementOrTreeIndex), true);
return cellText == aNewValue;
}
- else {
- if (!aNewValue && aElementOrTreeIndex.localName != "toolbarbutton")
- return aElementOrTreeIndex.getAttribute("label") == PlacesUIUtils.getBestTitle(aElementOrTreeIndex._placesNode);
- return aElementOrTreeIndex.getAttribute("label") == aNewValue;
+ if (!aNewValue && aElementOrTreeIndex.localName != "toolbarbutton") {
+ return aElementOrTreeIndex.getAttribute("label") == PlacesUIUtils.getBestTitle(aElementOrTreeIndex._placesNode);
}
+ return aElementOrTreeIndex.getAttribute("label") == aNewValue;
};
for (var i = 0; i < views.length; i++) {
var [node, index, valid] = searchItemInView(aItemId, views[i], validator);
isnot(node, null, "Found changed Places node in " + views[i]);
is(node.title, aNewValue, "Node has correct title: " + aNewValue);
ok(valid, "Node element has correct label: " + aNewValue);
}
--- a/browser/extensions/pocket/content/panels/js/saved.js
+++ b/browser/extensions/pocket/content/panels/js/saved.js
@@ -198,20 +198,18 @@ var PKT_SAVED_OVERLAY = function (option
myself.showTagsError(myself.dictJSON.maxtaglength);
changestamp = Date.now();
setTimeout(function() {
$('.token-input-input-token input').val(text).focus();
},10);
}
return null;
}
- else {
- myself.hideTagsError();
- return {name:myself.sanitizeText(text.toLowerCase())};
- }
+ myself.hideTagsError();
+ return {name:myself.sanitizeText(text.toLowerCase())};
},
onReady: function() {
$('.token-input-dropdown').addClass('token-input-dropdown-tag');
inputwrapper.find('.token-input-input-token input').attr('placeholder',$('.tag-input').attr('placeholder')).css('width','200px');
if ($('.pkt_ext_suggestedtag_detail').length) {
myself.wrapper.find('.pkt_ext_suggestedtag_detail').on('click','.token_tag',function(e) {
e.preventDefault();
var tag = $(e.target);
@@ -429,22 +427,19 @@ var PKT_SAVED_OVERLAY = function (option
">": ">",
'"': '"',
"'": '''
};
if (typeof s !== 'string')
{
return '';
}
- else
- {
- return String(s).replace(/[&<>"']/g, function (str) {
- return sanitizeMap[str];
- });
- }
+ return String(s).replace(/[&<>"']/g, function (str) {
+ return sanitizeMap[str];
+ });
};
this.showStateFinalMsg = function(msg) {
this.wrapper.find('.pkt_ext_tag_detail').one('webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd',function(e)
{
$(this).off('webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd');
myself.preventCloseTimerCancel = true;
myself.startCloseTimer(myself.autocloseTimingFinalState);
myself.wrapper.find('.pkt_ext_detail h2').text(msg);
--- a/browser/extensions/pocket/content/panels/js/signup.js
+++ b/browser/extensions/pocket/content/panels/js/signup.js
@@ -43,22 +43,19 @@ var PKT_SIGNUP_OVERLAY = function (optio
">": ">",
'"': '"',
"'": '''
};
if (typeof s !== 'string')
{
return '';
}
- else
- {
- return String(s).replace(/[&<>"']/g, function (str) {
- return sanitizeMap[str];
- });
- }
+ return String(s).replace(/[&<>"']/g, function (str) {
+ return sanitizeMap[str];
+ });
};
this.getTranslations = function()
{
this.dictJSON = window.pocketStrings;
};
};
PKT_SIGNUP_OVERLAY.prototype = {
--- a/browser/extensions/pocket/test/head.js
+++ b/browser/extensions/pocket/test/head.js
@@ -56,13 +56,12 @@ function promisePocketDisabled() {
Services.prefs.setBoolPref("extensions.pocket.enabled", false);
});
}
function promisePocketReset() {
if (enabledOnStartup) {
info("reset is enabling pocket addon");
return promisePocketEnabled();
- } else {
- info("reset is disabling pocket addon");
- return promisePocketDisabled();
}
+ info("reset is disabling pocket addon");
+ return promisePocketDisabled();
}
--- a/browser/modules/RecentWindow.jsm
+++ b/browser/modules/RecentWindow.jsm
@@ -49,20 +49,19 @@ this.RecentWindow = {
// this is oldest to newest, so this gets a bit ugly
while (windowList.hasMoreElements()) {
let nextWin = windowList.getNext();
if (isSuitableBrowserWindow(nextWin))
win = nextWin;
}
}
return win;
- } else {
- let windowList = Services.wm.getZOrderDOMWindowEnumerator("navigator:browser", true);
- while (windowList.hasMoreElements()) {
- let win = windowList.getNext();
- if (isSuitableBrowserWindow(win))
- return win;
- }
- return null;
}
+ let windowList = Services.wm.getZOrderDOMWindowEnumerator("navigator:browser", true);
+ while (windowList.hasMoreElements()) {
+ let win = windowList.getNext();
+ if (isSuitableBrowserWindow(win))
+ return win;
+ }
+ return null;
}
};
--- a/toolkit/.eslintrc
+++ b/toolkit/.eslintrc
@@ -63,17 +63,17 @@
// No duplicate cases in switch statements
"no-duplicate-case": 2,
// No labels
"no-labels": 2,
// If an if block ends with a return no need for an else block
- // "no-else-return": 2,
+ "no-else-return": 2,
// No empty statements
// "no-empty": 2,
// No empty character classes in regex
"no-empty-character-class": 2,
// Disallow empty destructuring
--- a/toolkit/components/addoncompat/Prefetcher.jsm
+++ b/toolkit/components/addoncompat/Prefetcher.jsm
@@ -213,19 +213,18 @@ MethodOp.prototype.makeCacheEntry = func
let selfArgs = this.args;
let methodImpl = function(...args) {
if (args.length == selfArgs.length && args.every((v, i) => v === selfArgs[i])) {
return result;
}
if (fallback) {
return fallback.value(...args);
- } else {
- return obj[method](...args);
}
+ return obj[method](...args);
};
let desc = { configurable: false, enumerable: true, writable: false, value: methodImpl };
propMap.set(this.method, desc);
}
function CollectionOp(outputTable, inputTable)
{
@@ -407,19 +406,18 @@ var Prefetcher = {
item = item.map((elt) => {
if (!isPrimitive(elt)) {
if (!cpowIndexes.has(elt)) {
let index = cpows.length;
cpows.push(elt);
cpowIndexes.set(elt, index);
}
return {cpow: cpowIndexes.get(elt)};
- } else {
- return elt;
}
+ return elt;
});
prefetched.push(item);
}
return [prefetched, cpows];
},
--- a/toolkit/components/addoncompat/RemoteAddonsParent.jsm
+++ b/toolkit/components/addoncompat/RemoteAddonsParent.jsm
@@ -771,28 +771,26 @@ ComponentsUtilsInterposition.methods.San
// The principals we pass to the content process must use an
// Array object from the content process.
let array = new chromeGlobal.Array();
for (let i = 0; i < principals.length; i++) {
array[i] = principals[i];
}
return SandboxParent.makeContentSandbox(addon, chromeGlobal, array, ...rest);
- } else {
- return Components.utils.Sandbox(principals, ...rest);
}
+ return Components.utils.Sandbox(principals, ...rest);
};
ComponentsUtilsInterposition.methods.evalInSandbox =
function(addon, target, code, sandbox, ...rest) {
if (sandbox && Cu.isCrossProcessWrapper(sandbox)) {
return SandboxParent.evalInSandbox(code, sandbox, ...rest);
- } else {
- return Components.utils.evalInSandbox(code, sandbox, ...rest);
}
+ return Components.utils.evalInSandbox(code, sandbox, ...rest);
};
// This interposition handles cases where an add-on tries to import a
// chrome XUL node into a content document. It doesn't actually do the
// import, which we can't support. It just avoids throwing an
// exception.
var ContentDocumentInterposition = new Interposition("ContentDocumentInterposition");
--- a/toolkit/components/asyncshutdown/tests/xpcshell/head.js
+++ b/toolkit/components/asyncshutdown/tests/xpcshell/head.js
@@ -115,19 +115,18 @@ function makeLock(kind) {
addBlocker: client.addBlocker,
removeBlocker: client.removeBlocker,
wait: function() {
return new Promise(resolve => {
barrier.wait(resolve);
});
}
};
- } else {
- throw new TypeError("Unknown kind " + kind);
}
+ throw new TypeError("Unknown kind " + kind);
}
makeLock.counter = 0;
makeLock.xpcomMap = new Map(); // Note: Not a WeakMap as we wish to handle non-gc-able keys (e.g. strings)
/**
* An asynchronous task that takes several ticks to complete.
*
* @param {*=} resolution The value with which the resulting promise will be
--- a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js
+++ b/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js
@@ -36,19 +36,18 @@ add_task(function* test_phase_simple_asy
do_print("Asynchronous test with " + arg + ", " + resolution + ", " + kind);
let lock = makeLock(kind);
let outParam = { isFinished: false };
lock.addBlocker(
"Async test",
function() {
if (success) {
return longRunningAsyncTask(resolution, outParam);
- } else {
- throw resolution;
}
+ throw resolution;
},
...state
);
do_check_false(outParam.isFinished);
yield lock.wait();
do_check_eq(outParam.isFinished, success);
}
}
--- a/toolkit/components/autocomplete/tests/unit/test_previousResult.js
+++ b/toolkit/components/autocomplete/tests/unit/test_previousResult.js
@@ -257,20 +257,18 @@ function run_test() {
if (numSearchesStarted == 1) {
do_check_eq(search1._previousResult, null);
do_check_eq(search2._previousResult, null);
// Now start it again
controller.startSearch("test");
return;
}
- else {
- do_check_neq(search1._previousResult, null);
- do_check_neq(search2._previousResult, null);
- }
+ do_check_neq(search1._previousResult, null);
+ do_check_neq(search2._previousResult, null);
// Unregister searches
unregisterAutoCompleteSearch(search1);
unregisterAutoCompleteSearch(search2);
do_test_finished();
};
--- a/toolkit/components/crashes/CrashManagerTest.jsm
+++ b/toolkit/components/crashes/CrashManagerTest.jsm
@@ -125,19 +125,18 @@ this.TestingCrashManager.prototype = {
* We can probably delete this once we have actual events defined.
*/
_handleEventFilePayload: function (store, entry, type, date, payload) {
if (type == "test.1") {
if (payload == "malformed") {
return this.EVENT_FILE_ERROR_MALFORMED;
} else if (payload == "success") {
return this.EVENT_FILE_SUCCESS;
- } else {
- return this.EVENT_FILE_ERROR_UNKNOWN_EVENT;
}
+ return this.EVENT_FILE_ERROR_UNKNOWN_EVENT;
}
return CrashManager.prototype._handleEventFilePayload.call(this,
store,
entry,
type,
date,
payload);
--- a/toolkit/components/extensions/Extension.jsm
+++ b/toolkit/components/extensions/Extension.jsm
@@ -1261,19 +1261,18 @@ MockExtension.prototype = {
resolve(this._readyPromise);
},
};
install.addListener(listener);
install.install();
});
});
- } else {
- throw Error("installType must be one of: temporary, permanent");
}
+ throw new Error("installType must be one of: temporary, permanent");
},
shutdown() {
this.addon.uninstall(true);
return this.cleanupGeneratedFile();
},
cleanupGeneratedFile() {
--- a/toolkit/components/extensions/ExtensionContent.jsm
+++ b/toolkit/components/extensions/ExtensionContent.jsm
@@ -526,21 +526,21 @@ DocumentManager = {
Services.obs.removeObserver(this, "document-element-inserted");
Services.obs.removeObserver(this, "inner-window-destroyed");
},
getWindowState(contentWindow) {
let readyState = contentWindow.document.readyState;
if (readyState == "complete") {
return "document_idle";
- } else if (readyState == "interactive") {
+ }
+ if (readyState == "interactive") {
return "document_end";
- } else {
- return "document_start";
}
+ return "document_start";
},
observe: function(subject, topic, data) {
if (topic == "document-element-inserted") {
let document = subject;
let window = document && document.defaultView;
if (!document || !document.location || !window) {
return;
--- a/toolkit/components/extensions/ExtensionManagement.jsm
+++ b/toolkit/components/extensions/ExtensionManagement.jsm
@@ -42,21 +42,21 @@ var Frames = {
return this.topWindowIds.has(windowId);
},
// Convert an outer window ID to a frame ID. An outer window ID of 0
// is invalid.
getId(windowId) {
if (this.isTopWindowId(windowId)) {
return 0;
- } else if (windowId == 0) {
+ }
+ if (windowId == 0) {
return -1;
- } else {
- return windowId;
}
+ return windowId;
},
// Convert an outer window ID for a parent window to a frame
// ID. Outer window IDs follow the same convention that
// |window.top.parent === window.top|. The API works differently,
// giving a frame ID of -1 for the the parent of a top-level
// window. This function handles the conversion.
getParentId(parentWindowId, windowId) {
--- a/toolkit/components/extensions/ExtensionUtils.jsm
+++ b/toolkit/components/extensions/ExtensionUtils.jsm
@@ -669,21 +669,20 @@ LocaleData.prototype = {
let replacer = (matched, index, dollarSigns) => {
if (index) {
// This is not quite Chrome-compatible. Chrome consumes any number
// of digits following the $, but only accepts 9 substitutions. We
// accept any number of substitutions.
index = parseInt(index, 10) - 1;
return index in substitutions ? substitutions[index] : "";
- } else {
- // For any series of contiguous `$`s, the first is dropped, and
- // the rest remain in the output string.
- return dollarSigns;
}
+ // For any series of contiguous `$`s, the first is dropped, and
+ // the rest remain in the output string.
+ return dollarSigns;
};
return str.replace(/\$(?:([1-9]\d*)|(\$+))/g, replacer);
}
}
// Check for certain pre-defined messages.
if (message == "@@ui_locale") {
return this.uiLocale;
--- a/toolkit/components/extensions/Schemas.jsm
+++ b/toolkit/components/extensions/Schemas.jsm
@@ -1118,35 +1118,33 @@ class CallEntry extends Entry {
return check(parameterIndex + 1, argIndex + 1);
};
if (this.allowAmbiguousOptionalArguments) {
// When this option is set, it's up to the implementation to
// parse arguments.
return args;
- } else {
- let success = check(0, 0);
- if (!success) {
- this.throwError(context, "Incorrect argument types");
- }
+ }
+ let success = check(0, 0);
+ if (!success) {
+ this.throwError(context, "Incorrect argument types");
}
// Now we normalize (and fully type check) all non-omitted arguments.
fixedArgs = fixedArgs.map((arg, parameterIndex) => {
if (arg === null) {
return null;
- } else {
- let parameter = this.parameters[parameterIndex];
- let r = parameter.type.normalize(arg, context);
- if (r.error) {
- this.throwError(context, `Type error for parameter ${parameter.name} (${r.error})`);
- }
- return r.value;
}
+ let parameter = this.parameters[parameterIndex];
+ let r = parameter.type.normalize(arg, context);
+ if (r.error) {
+ this.throwError(context, `Type error for parameter ${parameter.name} (${r.error})`);
+ }
+ return r.value;
});
return fixedArgs;
}
}
// Represents a "function" defined in a schema namespace.
class FunctionEntry extends CallEntry {
@@ -1312,19 +1310,18 @@ this.Schemas = {
let enumeration = type.enum || null;
if (enumeration) {
// The "enum" property is either a list of strings that are
// valid values or else a list of {name, description} objects,
// where the .name values are the valid values.
enumeration = enumeration.map(e => {
if (typeof(e) == "object") {
return e.name;
- } else {
- return e;
}
+ return e;
});
}
let pattern = null;
if (type.pattern) {
try {
pattern = parsePattern(type.pattern);
} catch (e) {
@@ -1436,19 +1433,18 @@ this.Schemas = {
}
checkTypeProperties("parameters", "async", "returns");
return new FunctionType(type, parameters, isAsync, hasAsyncCallback);
} else if (type.type == "any") {
// Need to see what minimum and maximum are supposed to do here.
checkTypeProperties("minimum", "maximum");
return new AnyType(type);
- } else {
- throw new Error(`Unexpected type ${type.type}`);
}
+ throw new Error(`Unexpected type ${type.type}`);
},
parseFunction(path, fun) {
let f = new FunctionEntry(fun, path, fun.name,
this.parseType(path, fun,
["name", "unsupported", "returns",
"permissions",
"allowAmbiguousOptionalArguments"]),
@@ -1587,35 +1583,35 @@ this.Schemas = {
if (namespace.permissions) {
let ns = this.namespaces.get(name);
ns.permissions = namespace.permissions;
}
}
};
if (Services.appinfo.processType != Services.appinfo.PROCESS_TYPE_CONTENT) {
- return readJSON(url).then(json => {
+ let result = readJSON(url).then(json => {
this.schemaJSON.set(url, json);
let data = Services.ppmm.initialProcessData;
data["Extension:Schemas"] = this.schemaJSON;
Services.ppmm.broadcastAsyncMessage("Schema:Add", {url, schema: json});
loadFromJSON(json);
});
- } else {
- if (this.loadedUrls.has(url)) {
- return;
- }
- this.loadedUrls.add(url);
+ return result;
+ }
+ if (this.loadedUrls.has(url)) {
+ return;
+ }
+ this.loadedUrls.add(url);
- let schema = this.schemaJSON.get(url);
- loadFromJSON(schema);
- }
+ let schema = this.schemaJSON.get(url);
+ loadFromJSON(schema);
},
inject(dest, wrapperFuncs) {
let context = new Context(wrapperFuncs);
for (let [namespace, ns] of this.namespaces) {
if (ns.permissions && !ns.permissions.some(perm => context.hasPermission(perm))) {
continue;
--- a/toolkit/components/extensions/ext-downloads.js
+++ b/toolkit/components/extensions/ext-downloads.js
@@ -240,19 +240,18 @@ function downloadQuery(query) {
queryTerms.push(term.toLowerCase());
}
}
}
function normalizeDownloadTime(arg, before) {
if (arg == null) {
return before ? Number.MAX_VALUE : 0;
- } else {
- return normalizeTime(arg).getTime();
}
+ return normalizeTime(arg).getTime();
}
const startedBefore = normalizeDownloadTime(query.startedBefore, true);
const startedAfter = normalizeDownloadTime(query.startedAfter, false);
// const endedBefore = normalizeDownloadTime(query.endedBefore, true);
// const endedAfter = normalizeDownloadTime(query.endedAfter, false);
const totalBytesGreater = query.totalBytesGreater || 0;
@@ -274,19 +273,18 @@ function downloadQuery(query) {
}
if (value == null) {
return input => re.test(input);
}
value = value.toLowerCase();
if (re.test(value)) {
return input => (value == input);
- } else {
- return input => false;
}
+ return input => false;
}
const matchFilename = makeMatch(query.filenameRegex, query.filename, "filename");
const matchUrl = makeMatch(query.urlRegex, query.url, "url");
return function(item) {
const url = item.url.toLowerCase();
const filename = item.filename.toLowerCase();
@@ -565,19 +563,18 @@ extensions.registerSchemaAPI("downloads"
});
},
open(downloadId) {
return DownloadMap.lazyInit().then(() => {
let download = DownloadMap.fromId(downloadId).download;
if (download.succeeded) {
return download.launch();
- } else {
- return Promise.reject({message: "Download has not completed."});
}
+ return Promise.reject({message: "Download has not completed."});
}).catch((error) => {
return Promise.reject({message: error.message});
});
},
show(downloadId) {
return DownloadMap.lazyInit().then(() => {
let download = DownloadMap.fromId(downloadId);
--- a/toolkit/components/extensions/test/mochitest/test_ext_permission_xhr.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_permission_xhr.html
@@ -33,21 +33,23 @@ add_task(function* test_simple() {
function passListener() {
browser.test.succeed(`${cx}.${fetch.name} pass listener`);
}
function failListener() {
browser.test.fail(`${cx}.${fetch.name} fail listener`);
}
+ /* eslint-disable no-else-return */
if (shouldFail) {
return fetch("http://example.org/example.txt").then(failListener, passListener);
} else {
return fetch("http://example.com/example.txt").then(passListener, failListener);
}
+ /* eslint-enable no-else-return */
}
return run(true, xhr(XMLHttpRequest))
.then(() => run(false, xhr(XMLHttpRequest)))
.then(() => run(true, xhr(window.XMLHttpRequest)))
.then(() => run(false, xhr(window.XMLHttpRequest)))
.then(() => run(true, fetch))
.then(() => run(false, fetch))
--- a/toolkit/components/feeds/FeedProcessor.js
+++ b/toolkit/components/feeds/FeedProcessor.js
@@ -1602,18 +1602,17 @@ FeedProcessor.prototype = {
_prefixForNS: function FP_prefixForNS(uri) {
if (!uri)
return "";
var prefix = gNamespaces[uri];
if (prefix)
return prefix + ":";
if (uri.toLowerCase().indexOf("http://backend.userland.com") == 0)
return "";
- else
- return null;
+ return null;
},
_mapAttributes: function FP__mapAttributes(bag, attributes) {
// Cycle through the attributes, and set our properties using the
// prefix:localNames we find in our namespace dictionary.
for (var i = 0; i < attributes.length; ++i) {
var key = this._prefixForNS(attributes.getURI(i)) + attributes.getLocalName(i);
var val = attributes.getValue(i);
@@ -1692,20 +1691,18 @@ FeedProcessor.prototype = {
}
}
catch(e) {
// ignore XPConnect errors
}
// the rest of the function deals with entry- and feed-level stuff
return;
}
- else {
- container = container.queryElementAt(container.length - 1,
- Ci.nsIWritablePropertyBag2);
- }
+ container = container.queryElementAt(container.length - 1,
+ Ci.nsIWritablePropertyBag2);
}
// Make the buffer our new property
var propName = this._prefixForNS(uri) + localName;
// But, it could be something containing HTML. If so,
// we need to know about that.
if (this._textConstructs[propName] != null &&
--- a/toolkit/components/jsdownloads/src/DownloadCore.jsm
+++ b/toolkit/components/jsdownloads/src/DownloadCore.jsm
@@ -1001,20 +1001,19 @@ this.Download.prototype = {
this._finalized = true;
if (aRemovePartialData) {
// Cancel the download, in case it is currently in progress, then remove
// any partially downloaded data. The removal operation waits for
// cancellation to be completed before resolving the promise it returns.
this.cancel();
return this.removePartialData();
- } else {
- // Just cancel the download, in case it is currently in progress.
- return this.cancel();
}
+ // Just cancel the download, in case it is currently in progress.
+ return this.cancel();
},
/**
* Indicates the time of the last progress notification, expressed as the
* number of milliseconds since January 1, 1970, 00:00:00 UTC. This is zero
* until some bytes have actually been transferred.
*/
_lastProgressTimeMs: 0,
--- a/toolkit/components/jsdownloads/src/DownloadList.jsm
+++ b/toolkit/components/jsdownloads/src/DownloadList.jsm
@@ -307,19 +307,18 @@ this.DownloadCombinedList.prototype = {
* @return {Promise}
* @resolves When the download has been added.
* @rejects JavaScript exception.
*/
add: function (aDownload)
{
if (aDownload.source.isPrivate) {
return this._privateList.add(aDownload);
- } else {
- return this._publicList.add(aDownload);
}
+ return this._publicList.add(aDownload);
},
/**
* Removes a download from the list. If the download was already removed,
* this method has no effect.
*
* This method does not change the state of the download, to allow adding it
* to another list, or control it directly. If you want to dispose of the
@@ -332,19 +331,18 @@ this.DownloadCombinedList.prototype = {
* @return {Promise}
* @resolves When the download has been removed.
* @rejects JavaScript exception.
*/
remove: function (aDownload)
{
if (aDownload.source.isPrivate) {
return this._privateList.remove(aDownload);
- } else {
- return this._publicList.remove(aDownload);
}
+ return this._publicList.remove(aDownload);
},
//////////////////////////////////////////////////////////////////////////////
//// DownloadList view
onDownloadAdded: function (aDownload)
{
this._downloads.push(aDownload);
--- a/toolkit/components/microformats/microformat-shiv.js
+++ b/toolkit/components/microformats/microformat-shiv.js
@@ -127,20 +127,19 @@ var Microformats; // jshint ignore:line
* @return {Object}
*/
getParent: function(node, options) {
this.init();
options = (options)? options : {};
if(node){
return this.getParentTreeWalk(node, options);
- }else{
- this.errors.push(this.noContentErr);
- return this.formatError();
}
+ this.errors.push(this.noContentErr);
+ return this.formatError();
},
/**
* get the count of microformats
*
* @param {DOM Node} rootNode
* @return {Int}
@@ -154,44 +153,42 @@ var Microformats; // jshint ignore:line
this.init();
options = (options)? options : {};
this.getDOMContext( options );
// if we do not have any context create error
if(!this.rootNode || !this.document){
return {'errors': [this.noContentErr]};
- }else{
-
- items = this.findRootNodes( this.rootNode, true );
- i = items.length;
- while(i--) {
- classItems = modules.domUtils.getAttributeList(items[i], 'class');
- x = classItems.length;
- while(x--) {
- // find v2 names
- if(modules.utils.startWith( classItems[x], 'h-' )){
- this.appendCount(classItems[x], 1, out);
- }
- // find v1 names
- for(var key in modules.maps) {
- // dont double count if v1 and v2 roots are present
- if(modules.maps[key].root === classItems[x] && classItems.indexOf(key) === -1) {
- this.appendCount(key, 1, out);
- }
+ }
+ items = this.findRootNodes( this.rootNode, true );
+ i = items.length;
+ while(i--) {
+ classItems = modules.domUtils.getAttributeList(items[i], 'class');
+ x = classItems.length;
+ while(x--) {
+ // find v2 names
+ if(modules.utils.startWith( classItems[x], 'h-' )){
+ this.appendCount(classItems[x], 1, out);
+ }
+ // find v1 names
+ for(var key in modules.maps) {
+ // dont double count if v1 and v2 roots are present
+ if(modules.maps[key].root === classItems[x] && classItems.indexOf(key) === -1) {
+ this.appendCount(key, 1, out);
}
}
}
- var relCount = this.countRels( this.rootNode );
- if(relCount > 0){
- out.rels = relCount;
- }
-
- return out;
}
+ var relCount = this.countRels( this.rootNode );
+ if(relCount > 0){
+ out.rels = relCount;
+ }
+
+ return out;
},
/**
* does a node have a class that marks it as a microformats root
*
* @param {DOM Node} node
* @param {Objecte} options
@@ -213,19 +210,18 @@ var Microformats; // jshint ignore:line
if(options && options.filters && modules.utils.isArray(options.filters)){
i = options.filters.length;
while(i--) {
if(classes.root.indexOf(options.filters[i]) > -1){
return true;
}
}
return false;
- }else{
- return (classes.root.length > 0);
}
+ return (classes.root.length > 0);
},
/**
* does a node or its children have microformats
*
* @param {DOM Node} node
* @param {Objecte} options
@@ -247,19 +243,18 @@ var Microformats; // jshint ignore:line
if(options && options.filters && modules.utils.isArray(options.filters)){
i = items.length;
while(i--) {
if( this.isMicroformat( items[i], options ) ){
return true;
}
}
return false;
- }else{
- return (items.length > 0);
}
+ return (items.length > 0);
},
/**
* add a new v1 mapping object to parser
*
* @param {Array} maps
*/
@@ -282,31 +277,28 @@ var Microformats; // jshint ignore:line
*/
getParentTreeWalk: function (node, options, recursive) {
options = (options)? options : {};
// recursive calls
if (recursive === undefined) {
if (node.parentNode && node.nodeName !== 'HTML'){
return this.getParentTreeWalk(node.parentNode, options, true);
- }else{
- return this.formatEmpty();
}
+ return this.formatEmpty();
}
if (node !== null && node !== undefined && node.parentNode) {
if (this.isMicroformat( node, options )) {
// if we have a match return microformat
options.node = node;
return this.get( options );
- }else{
- return this.getParentTreeWalk(node.parentNode, options, true);
}
- }else{
- return this.formatEmpty();
+ return this.getParentTreeWalk(node.parentNode, options, true);
}
+ return this.formatEmpty();
},
/**
* configures what are the base DOM objects for parsing
*
* @param {Object} options
@@ -468,19 +460,18 @@ var Microformats; // jshint ignore:line
if(modules.utils.isArray(filters) && filters.length > 0) {
i = filters.length;
while(i--) {
if(uf.type[0] === filters[i]) {
return true;
}
}
return false;
- } else {
- return true;
}
+ return true;
},
/**
* finds all microformat roots in a rootNode
*
* @param {DOM Node} rootNode
* @param {Boolean} includeRoot
@@ -960,26 +951,24 @@ var Microformats; // jshint ignore:line
// just duration
return out;
} else if(modules.dates.isTime(out)) {
// just time or time+timezone
if(uf) {
uf.times.push([className, modules.dates.parseAmPmTime(out, this.options.dateFormat)]);
}
return modules.dates.parseAmPmTime(out, this.options.dateFormat);
- } else {
- // returns a date - microformat profile
- if(uf) {
- uf.dates.push([className, new modules.ISODate(out).toString( this.options.dateFormat )]);
- }
- return new modules.ISODate(out).toString( this.options.dateFormat );
}
- } else {
- return '';
+ // returns a date - microformat profile
+ if(uf) {
+ uf.dates.push([className, new modules.ISODate(out).toString( this.options.dateFormat )]);
+ }
+ return new modules.ISODate(out).toString( this.options.dateFormat );
}
+ return '';
},
/**
* appends a new rootid to a given node
*
* @param {DOM Node} node
* @param {String} id
@@ -1004,20 +993,19 @@ var Microformats; // jshint ignore:line
* @param {String} id
* @param {String} propertyName
* @return {Boolean}
*/
hasRootID: function(node, id, propertyName) {
var rootids = [];
if(!modules.domUtils.hasAttribute(node,'rootids')){
return false;
- } else {
- rootids = modules.domUtils.getAttributeList(node, 'rootids');
- return (rootids.indexOf('id' + id + '-' + propertyName) > -1);
}
+ rootids = modules.domUtils.getAttributeList(node, 'rootids');
+ return (rootids.indexOf('id' + id + '-' + propertyName) > -1);
},
/**
* gets the text of any child nodes with a class value
*
* @param {DOM Node} node
@@ -1063,19 +1051,18 @@ var Microformats; // jshint ignore:line
}
if(propertyType === 'u') {
return out.join('');
}
if(propertyType === 'dt') {
return modules.dates.concatFragments(out,this.options.dateFormat).toString(this.options.dateFormat);
}
return undefined;
- } else {
- return null;
}
+ return null;
},
/**
* returns a single string of the 'title' attr from all
* the child nodes with the class 'value-title'
*
* @param {DOM Node} node
@@ -1105,19 +1092,18 @@ var Microformats; // jshint ignore:line
*
* @param {DOM Node} node
* @return {Boolean}
*/
hasHClass: function(node){
var classes = this.getUfClassNames(node);
if(classes.root && classes.root.length > 0){
return true;
- }else{
- return false;
}
+ return false;
},
/**
* get both the root and property class names from a node
*
* @param {DOM Node} node
* @param {Array} ufNameArr
@@ -1307,19 +1293,18 @@ var Microformats; // jshint ignore:line
*
* @param {String} typeVersion
* @param {String} propertyVersion
* @return {Boolean}
*/
isAllowedPropertyVersion: function(typeVersion, propertyVersion){
if(this.options.overlappingVersions === true){
return true;
- }else{
- return (typeVersion === propertyVersion);
}
+ return (typeVersion === propertyVersion);
},
/**
* creates a blank microformats object
*
* @param {String} name
* @param {String} value
@@ -2275,36 +2260,34 @@ var Microformats; // jshint ignore:line
* removes spaces at front and back of text
*
* @param {String} text
* @return {String}
*/
trim: function( text ) {
if(text && this.isString(text)){
return (text.trim())? text.trim() : text.replace(/^\s+|\s+$/g, '');
- }else{
- return '';
}
+ return '';
},
/**
* replaces a character in text
*
* @param {String} text
* @param {Int} index
* @param {String} character
* @return {String}
*/
replaceCharAt: function( text, index, character ) {
if(text && text.length > index){
return text.substr(0, index) + character + text.substr(index+character.length);
- }else{
- return text;
}
+ return text;
},
/**
* removes whitespace, tabs and returns from start and end of text
*
* @param {String} text
* @return {String}
@@ -2752,19 +2735,18 @@ var Microformats; // jshint ignore:line
// count all elements
out = child;
countAll++;
}
}
}
if(onlyOfType === true){
return (countOfType === 1)? out : null;
- }else{
- return (countAll === 1)? out : null;
}
+ return (countAll === 1)? out : null;
},
/**
* is a node one of a list of tags
*
* @param {DOM Node} rootNode
* @param {Array} tagNames
@@ -2797,19 +2779,18 @@ var Microformats; // jshint ignore:line
* abstracts DOM removeChild
*
* @param {DOM Node} childNode
* @return {DOM Node || null}
*/
removeChild: function(childNode){
if (childNode.parentNode) {
return childNode.parentNode.removeChild(childNode);
- }else{
- return null;
}
+ return null;
},
/**
* abstracts DOM cloneNode
*
* @param {DOM Node} node
* @return {DOM Node}
@@ -2825,19 +2806,18 @@ var Microformats; // jshint ignore:line
* gets the text of a node
*
* @param {DOM Node} node
* @return {String}
*/
getElementText: function( node ){
if(node && node.data){
return node.data;
- }else{
- return '';
}
+ return '';
},
/**
* gets the attributes of a node - ordered by sequence in html
*
* @param {DOM Node} node
* @return {Array}
@@ -3673,22 +3653,21 @@ var Microformats; // jshint ignore:line
isotime.parseTime(this.parseAmPmTime(time), format);
if(isodate.hasFullDate() && isotime.hasTime()) {
isodate.tH = isotime.tH;
isodate.tM = isotime.tM;
isodate.tS = isotime.tS;
isodate.tD = isotime.tD;
return isodate;
- } else {
- if(isodate.hasFullDate()){
- return isodate;
- }
- return new modules.ISODate();
}
+ if(isodate.hasFullDate()){
+ return isodate;
+ }
+ return new modules.ISODate();
},
/**
* concatenate an array of date and time text fragments to create an ISODate object
* used for microformat value and value-title rules
*
* @param {Array} arr ( Array of Strings )
@@ -3698,18 +3677,18 @@ var Microformats; // jshint ignore:line
concatFragments: function (arr, format) {
var out = new modules.ISODate(),
i = 0,
value = '';
// if the fragment already contains a full date just return it once
if(arr[0].toUpperCase().match('T')) {
return new modules.ISODate(arr[0], format);
- }else{
- for(i = 0; i < arr.length; i++) {
+ }
+ for(i = 0; i < arr.length; i++) {
value = arr[i];
// date pattern
if( value.charAt(4) === '-' && out.hasFullDate() === false ){
out.parseDate(value);
}
// time pattern
@@ -3732,18 +3711,16 @@ var Microformats; // jshint ignore:line
if(value.charAt(0) === '-' || value.charAt(0) === '+' || value.toUpperCase() === 'Z') {
if( out.hasTimeZone() === false ){
out.parseTimeZone(value);
}
}
}
return out;
-
- }
},
/**
* parses text by splitting it into an array of time and timezone strings
*
* @param {String} text
* @return {Array} Modules.ISODate
@@ -3791,22 +3768,20 @@ var Microformats; // jshint ignore:line
*/
parse: function(doc, node, textFormat){
var out;
this.textFormat = (textFormat)? textFormat : this.textFormat;
if(this.textFormat === 'normalised'){
out = this.walkTreeForText( node );
if(out !== undefined){
return this.normalise( doc, out );
- }else{
- return '';
}
- }else{
- return this.formatText( doc, modules.domUtils.textContent(node), this.textFormat );
+ return '';
}
+ return this.formatText( doc, modules.domUtils.textContent(node), this.textFormat );
},
/**
* parses the text from a html string
*
* @param {DOM Document} doc
* @param {String} text
@@ -3834,19 +3809,18 @@ var Microformats; // jshint ignore:line
out = text.replace(regex, '');
if(this.textFormat === 'whitespacetrimmed') {
out = modules.utils.trimWhitespace( out );
}
//return entities.decode( out, 2 );
return modules.domUtils.decodeEntities( doc, out );
- }else{
- return '';
}
+ return '';
},
/**
* normalises whitespace in given text
*
* @param {String} text
* @return {String}
--- a/toolkit/components/passwordmgr/nsLoginManagerPrompter.js
+++ b/toolkit/components/passwordmgr/nsLoginManagerPrompter.js
@@ -254,24 +254,23 @@ LoginManagerPrompter.prototype = {
return this.__ellipsis;
},
// Whether we are in private browsing mode
get _inPrivateBrowsing() {
if (this._window) {
return PrivateBrowsingUtils.isContentWindowPrivate(this._window);
- } else {
- // If we don't that we're in private browsing mode if the caller did
- // not provide a window. The callers which really care about this
- // will indeed pass down a window to us, and for those who don't,
- // we can just assume that we don't want to save the entered login
- // information.
- return true;
}
+ // If we don't that we're in private browsing mode if the caller did
+ // not provide a window. The callers which really care about this
+ // will indeed pass down a window to us, and for those who don't,
+ // we can just assume that we don't want to save the entered login
+ // information.
+ return true;
},
/* ---------- nsIAuthPrompt prompts ---------- */
@@ -1479,18 +1478,17 @@ LoginManagerPrompter.prototype = {
* Returns the localized string for the specified key,
* formatted if required.
*
*/
_getLocalizedString : function (key, formatArgs) {
if (formatArgs)
return this._strBundle.formatStringFromName(
key, formatArgs, formatArgs.length);
- else
- return this._strBundle.GetStringFromName(key);
+ return this._strBundle.GetStringFromName(key);
},
/**
* Sanitizes the specified username, by stripping quotes and truncating if
* it's too long. This helps prevent an evil site from messing with the
* "save password?" prompt too much.
*/
--- a/toolkit/components/perfmonitoring/tests/browser/browser_addonPerformanceAlerts.js
+++ b/toolkit/components/perfmonitoring/tests/browser/browser_addonPerformanceAlerts.js
@@ -36,20 +36,19 @@ add_task(function* test_install_addon_th
let universalListener = new AddonListener("*", alerts => {
info(`AddonListener: received alerts ${JSON.stringify(alerts)}`);
let alert = alerts.find(({source}) => {
return source.addonId == addon.addonId;
});
if (alert) {
info(`AddonListener: I found an alert for ${addon.addonId}`);
return alert.details.highestJank;
- } else {
- info(`AddonListener: I didn't find any alert for ${addon.addonId}`);
- return null;
}
+ info(`AddonListener: I didn't find any alert for ${addon.addonId}`);
+ return null;
});
// Waiting a little – listeners are buffered.
yield new Promise(resolve => setTimeout(resolve, 100));
yield addon.run(topic, 10, realListener);
// Waiting a little – listeners are buffered.
yield new Promise(resolve => setTimeout(resolve, 100));
--- a/toolkit/components/places/BookmarkHTMLUtils.jsm
+++ b/toolkit/components/places/BookmarkHTMLUtils.jsm
@@ -879,19 +879,18 @@ BookmarkImporter.prototype = {
},
/**
* Converts a string date in seconds to an int date in microseconds
*/
_convertImportedDateToInternalDate: function convertImportedDateToInternalDate(aDate) {
if (aDate && !isNaN(aDate)) {
return parseInt(aDate) * 1000000; // in bookmarks.html this value is in seconds, not microseconds
- } else {
- return Date.now();
}
+ return Date.now();
},
runBatched: function runBatched(aDoc) {
if (!aDoc) {
return;
}
if (this._isImportDefaults) {
--- a/toolkit/components/places/PlacesBackups.jsm
+++ b/toolkit/components/places/PlacesBackups.jsm
@@ -200,19 +200,18 @@ this.PlacesBackups = {
return undefined;
}
if (filenamesRegex.test(aEntry.name)) {
// Remove bogus backups in future dates.
let filePath = aEntry.path;
if (this.getDateForFile(filePath) > new Date()) {
return OS.File.remove(filePath);
- } else {
- this._backupFiles.push(filePath);
}
+ this._backupFiles.push(filePath);
}
return undefined;
}.bind(this));
iterator.close();
this._backupFiles.sort((a, b) => {
let aDate = this.getDateForFile(a);
--- a/toolkit/components/places/tests/head_common.js
+++ b/toolkit/components/places/tests/head_common.js
@@ -733,20 +733,18 @@ function do_check_guid_for_bookmark(aId,
function do_compare_arrays(a1, a2, sorted)
{
if (a1.length != a2.length)
return false;
if (sorted) {
return a1.every((e, i) => e == a2[i]);
}
- else {
- return a1.filter(e => !a2.includes(e)).length == 0 &&
- a2.filter(e => !a1.includes(e)).length == 0;
- }
+ return a1.filter(e => !a2.includes(e)).length == 0 &&
+ a2.filter(e => !a1.includes(e)).length == 0;
}
/**
* Generic nsINavBookmarkObserver that doesn't implement anything, but provides
* dummy methods to prevent errors about an object not having a certain method.
*/
function NavBookmarkObserver() {}
--- a/toolkit/components/places/tests/queries/test_redirects.js
+++ b/toolkit/components/places/tests/queries/test_redirects.js
@@ -45,38 +45,39 @@ function check_results_callback(aSequenc
}
return true;
});
// Remove duplicates, since queries are RESULTS_AS_URI (unique pages).
let seen = [];
expectedData = expectedData.filter(function (aData) {
- if (seen.includes(aData.uri))
+ if (seen.includes(aData.uri)) {
return false;
- else
- seen.push(aData.uri);
+ }
+ seen.push(aData.uri);
return true;
});
// Sort expectedData.
function getFirstIndexFor(aEntry) {
for (let i = 0; i < visits.length; i++) {
if (visits[i].uri == aEntry.uri)
return i;
}
return undefined;
}
function comparator(a, b) {
- if (sortingMode == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING)
+ if (sortingMode == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING) {
return b.lastVisit - a.lastVisit;
- else if (sortingMode == Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING)
+ }
+ if (sortingMode == Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING) {
return b.visitCount - a.visitCount;
- else
- return getFirstIndexFor(a) - getFirstIndexFor(b);
+ }
+ return getFirstIndexFor(a) - getFirstIndexFor(b);
}
expectedData.sort(comparator);
// Crop results to maxResults if it's defined.
if (maxResults) {
expectedData = expectedData.slice(0, maxResults);
}
--- a/toolkit/components/printing/content/printPageSetup.js
+++ b/toolkit/components/printing/content/printPageSetup.js
@@ -193,19 +193,18 @@ gHFValues[ "&PT" ] = 5;
function hfValueToId(val)
{
if ( val in gHFValues ) {
return gHFValues[val];
}
if ( val.length ) {
return 6; // Custom...
- } else {
- return 0; // --blank--
}
+ return 0; // --blank--
}
function hfIdToValue(node)
{
var result = "";
switch ( parseInt( node.value ) ) {
case 0:
break;
@@ -370,28 +369,26 @@ function onLoad()
alert("Could initialize gDialog, PrintSettings is null!");
}
}
function convertUnitsMarginToInches(aVal, aIsMetric)
{
if (aIsMetric) {
return aVal / 25.4;
- } else {
- return aVal;
}
+ return aVal;
}
function convertMarginInchesToUnits(aVal, aIsMetric)
{
if (aIsMetric) {
return aVal * 25.4;
- } else {
- return aVal;
}
+ return aVal;
}
//---------------------------------------------------
function onAccept()
{
if (gPrintSettings) {
if ( gDialog.orientation.selectedItem == gDialog.portrait ) {
--- a/toolkit/components/printing/content/printProgress.js
+++ b/toolkit/components/printing/content/printProgress.js
@@ -24,20 +24,19 @@ function ellipseString(aStr, doFront)
return aStr;
}
var fixedLen = 64;
if (aStr.length > fixedLen) {
if (doFront) {
var endStr = aStr.substr(aStr.length-fixedLen, fixedLen);
return "..." + endStr;
- } else {
- var frontStr = aStr.substr(0, fixedLen);
- return frontStr + "...";
}
+ var frontStr = aStr.substr(0, fixedLen);
+ return frontStr + "...";
}
return aStr;
}
// all progress notifications are done through the nsIWebProgressListener implementation...
var progressListener = {
onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus)
{
--- a/toolkit/components/promiseworker/PromiseWorker.jsm
+++ b/toolkit/components/promiseworker/PromiseWorker.jsm
@@ -274,19 +274,18 @@ this.BasePromiseWorker.prototype = {
if (args) {
// Extract `Meta` data
args = args.map(arg => {
if (arg instanceof BasePromiseWorker.Meta) {
if (arg.meta && "transfers" in arg.meta) {
transfers.push(...arg.meta.transfers);
}
return arg.data;
- } else {
- return arg;
}
+ return arg;
});
}
let id = ++this._id;
let message = {fun: fun, args: args, id: id};
this.log("Posting message", message);
try {
this._worker.postMessage(message, ...[transfers]);
--- a/toolkit/components/prompts/src/nsPrompter.js
+++ b/toolkit/components/prompts/src/nsPrompter.js
@@ -118,18 +118,17 @@ Prompter.prototype = {
// Common utils not specific to a particular prompter style.
var PromptUtilsTemp = {
__proto__ : PromptUtils,
getLocalizedString : function (key, formatArgs) {
if (formatArgs)
return this.strBundle.formatStringFromName(key, formatArgs, formatArgs.length);
- else
- return this.strBundle.GetStringFromName(key);
+ return this.strBundle.GetStringFromName(key);
},
confirmExHelper : function (flags, button0, button1, button2) {
const BUTTON_DEFAULT_MASK = 0x03000000;
let defaultButtonNum = (flags & BUTTON_DEFAULT_MASK) >> 24;
let isDelayEnabled = (flags & Ci.nsIPrompt.BUTTON_DELAY_ENABLE);
// Flags can be used to select a specific pre-defined button label or
@@ -565,34 +564,31 @@ ModalPrompter.prototype = {
* different arguments. All but prompt() have the same number of
* arguments, so look at the arg types to figure out how we're being
* called. :-(
*/
prompt : function() {
// also, the nsIPrompt flavor has 5 args instead of 6.
if (typeof arguments[2] == "object")
return this.nsIPrompt_prompt.apply(this, arguments);
- else
- return this.nsIAuthPrompt_prompt.apply(this, arguments);
+ return this.nsIAuthPrompt_prompt.apply(this, arguments);
},
promptUsernameAndPassword : function() {
// Both have 6 args, so use types.
if (typeof arguments[2] == "object")
return this.nsIPrompt_promptUsernameAndPassword.apply(this, arguments);
- else
- return this.nsIAuthPrompt_promptUsernameAndPassword.apply(this, arguments);
+ return this.nsIAuthPrompt_promptUsernameAndPassword.apply(this, arguments);
},
promptPassword : function() {
// Both have 5 args, so use types.
if (typeof arguments[2] == "object")
return this.nsIPrompt_promptPassword.apply(this, arguments);
- else
- return this.nsIAuthPrompt_promptPassword.apply(this, arguments);
+ return this.nsIAuthPrompt_promptPassword.apply(this, arguments);
},
/* ---------- nsIPrompt ---------- */
alert : function (title, text) {
if (!title)
--- a/toolkit/components/satchel/nsFormAutoComplete.js
+++ b/toolkit/components/satchel/nsFormAutoComplete.js
@@ -588,18 +588,17 @@ FormAutoCompleteResult.prototype = {
},
// Interfaces from idl...
searchString : "",
errorDescription : "",
get defaultIndex() {
if (this.entries.length == 0)
return -1;
- else
- return 0;
+ return 0;
},
get searchResult() {
if (this.entries.length == 0)
return Ci.nsIAutoCompleteResult.RESULT_NOMATCH;
return Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
},
get matchCount() {
return this.entries.length;
--- a/toolkit/components/satchel/test/unit/test_autocomplete.js
+++ b/toolkit/components/satchel/test/unit/test_autocomplete.js
@@ -15,20 +15,20 @@ const DEFAULT_EXPIRE_DAYS = 180;
function padLeft(number, length) {
var str = number + '';
while (str.length < length)
str = '0' + str;
return str;
}
function getFormExpiryDays() {
- if (prefs.prefHasUserValue("browser.formfill.expire_days"))
+ if (prefs.prefHasUserValue("browser.formfill.expire_days")) {
return prefs.getIntPref("browser.formfill.expire_days");
- else
- return DEFAULT_EXPIRE_DAYS;
+ }
+ return DEFAULT_EXPIRE_DAYS;
}
function run_test() {
// ===== test init =====
var testfile = do_get_file("formhistory_autocomplete.sqlite");
var profileDir = dirSvc.get("ProfD", Ci.nsIFile);
// Cleanup from any previous tests or failures.
--- a/toolkit/components/telemetry/TelemetrySend.jsm
+++ b/toolkit/components/telemetry/TelemetrySend.jsm
@@ -116,19 +116,18 @@ function isDeletionPing(aPing) {
* Save the provided ping as a pending ping. If it's a deletion ping, save it
* to a special location.
* @param {Object} aPing The ping to save.
* @return {Promise} A promise resolved when the ping is saved.
*/
function savePing(aPing) {
if (isDeletionPing(aPing)) {
return TelemetryStorage.saveDeletionPing(aPing);
- } else {
- return TelemetryStorage.savePendingPing(aPing);
}
+ return TelemetryStorage.savePendingPing(aPing);
}
/**
* @return {String} This returns a string with the gzip compressed data.
*/
function gzipCompressString(string) {
let observer = {
buffer: "",
@@ -840,19 +839,18 @@ var TelemetrySendImpl = {
SendScheduler.notifySendsFailed();
}
if (success && isPersisted) {
if (TelemetryStorage.isDeletionPing(id)) {
return TelemetryStorage.removeDeletionPing();
}
return TelemetryStorage.removePendingPing(id);
- } else {
- return Promise.resolve();
}
+ return Promise.resolve();
},
_getSubmissionPath: function(ping) {
// The new ping format contains an "application" section, the old one doesn't.
let pathComponents;
if (isV4PingFormat(ping)) {
// We insert the Ping id in the URL to simplify server handling of duplicated
// pings.
--- a/toolkit/components/telemetry/TelemetryStorage.jsm
+++ b/toolkit/components/telemetry/TelemetryStorage.jsm
@@ -659,19 +659,18 @@ var TelemetryStorageImpl = {
_saveArchivedPingTask: Task.async(function*(ping) {
const creationDate = new Date(ping.creationDate);
if (this._archivedPings.has(ping.id)) {
const data = this._archivedPings.get(ping.id);
if (data.timestampCreated > creationDate.getTime()) {
this._log.error("saveArchivedPing - trying to overwrite newer ping with the same id");
return Promise.reject(new Error("trying to overwrite newer ping with the same id"));
- } else {
- this._log.warn("saveArchivedPing - overwriting older ping with the same id");
}
+ this._log.warn("saveArchivedPing - overwriting older ping with the same id");
}
// Get the archived ping path and append the lz4 suffix to it (so we have 'jsonlz4').
const filePath = getArchivedPingPath(ping.id, creationDate, ping.type) + "lz4";
yield OS.File.makeDir(OS.Path.dirname(filePath), { ignoreExisting: true,
from: OS.Constants.Path.profileDir });
yield this.savePingToFile(ping, filePath, /*overwrite*/ true, /*compressed*/ true);
--- a/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js
+++ b/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js
@@ -87,20 +87,19 @@ function truncateDateToDays(date) {
0, 0, 0, 0);
}
function sendPing() {
TelemetrySession.gatherStartup();
if (PingServer.started) {
TelemetrySend.setServer("http://localhost:" + PingServer.port);
return TelemetrySession.testPing();
- } else {
- TelemetrySend.setServer("http://doesnotexist");
- return TelemetrySession.testPing();
}
+ TelemetrySend.setServer("http://doesnotexist");
+ return TelemetrySession.testPing();
}
function fakeGenerateUUID(sessionFunc, subsessionFunc) {
let session = Cu.import("resource://gre/modules/TelemetrySession.jsm");
session.Policy.generateSessionUUID = sessionFunc;
session.Policy.generateSubsessionUUID = subsessionFunc;
}
--- a/toolkit/content/aboutSupport.js
+++ b/toolkit/content/aboutSupport.js
@@ -92,20 +92,18 @@ var snapshotFormatters = {
reportURL = null;
}
catch (e) { }
if (!reportURL) {
$("crashes-noConfig").style.display = "block";
$("crashes-noConfig").classList.remove("no-copy");
return;
}
- else {
- $("crashes-allReports").style.display = "block";
- $("crashes-allReports").classList.remove("no-copy");
- }
+ $("crashes-allReports").style.display = "block";
+ $("crashes-allReports").classList.remove("no-copy");
if (data.pending > 0) {
$("crashes-allReportsWithPending").textContent =
PluralForm.get(data.pending, strings.GetStringFromName("pendingReports"))
.replace("#1", data.pending);
}
let dateNow = new Date();
--- a/toolkit/content/aboutTelemetry.js
+++ b/toolkit/content/aboutTelemetry.js
@@ -153,19 +153,18 @@ function getMainWindow() {
* pane.
*
* This may return null if we can't find the browser chrome window.
*/
function getMainWindowWithPreferencesPane() {
let mainWindow = getMainWindow();
if (mainWindow && "openAdvancedPreferences" in mainWindow) {
return mainWindow;
- } else {
- return null;
}
+ return null;
}
/**
* Remove all child nodes of a document node.
*/
function removeAllChildNodes(node) {
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
--- a/toolkit/content/contentAreaUtils.js
+++ b/toolkit/content/contentAreaUtils.js
@@ -1201,27 +1201,25 @@ function getDefaultExtension(aFilename,
url = aURI.QueryInterface(Components.interfaces.nsIURL);
urlext = url.fileExtension;
} catch (e) {
}
if (urlext && mimeInfo && mimeInfo.extensionExists(urlext)) {
return urlext;
}
- else {
- try {
- if (mimeInfo)
- return mimeInfo.primaryExtension;
- }
- catch (e) {
- }
- // Fall back on the extensions in the filename and URI for lack
- // of anything better.
- return ext || urlext;
+ try {
+ if (mimeInfo)
+ return mimeInfo.primaryExtension;
}
+ catch (e) {
+ }
+ // Fall back on the extensions in the filename and URI for lack
+ // of anything better.
+ return ext || urlext;
}
function GetSaveModeForContentType(aContentType, aDocument)
{
// We can only save a complete page if we have a loaded document,
// and it's not a CPOW -- nsWebBrowserPersist needs a real document.
if (!aDocument || Components.utils.isCrossProcessWrapper(aDocument))
return SAVEMODE_FILEONLY;
--- a/toolkit/content/tests/chrome/popup_trigger.js
+++ b/toolkit/content/tests/chrome/popup_trigger.js
@@ -128,36 +128,36 @@ var popupTests = [
result: function(testname) { checkActive(gMenuPopup, "item1", testname); }
},
{
// check cursor down when a disabled item exists in the menu
testname: "cursor down disabled",
events: function() {
// On Windows, disabled items are included when navigating, but on
// other platforms, disabled items are skipped over
- if (navigator.platform.indexOf("Win") == 0)
+ if (navigator.platform.indexOf("Win") == 0) {
return [ "DOMMenuItemInactive item1", "DOMMenuItemActive item2" ];
- else
- return [ "DOMMenuItemInactive item1", "DOMMenuItemActive amenu" ];
+ }
+ return [ "DOMMenuItemInactive item1", "DOMMenuItemActive amenu" ];
},
test: function() {
document.getElementById("item2").disabled = true;
synthesizeKey("VK_DOWN", { });
}
},
{
// check cursor up when a disabled item exists in the menu
testname: "cursor up disabled",
events: function() {
- if (navigator.platform.indexOf("Win") == 0)
+ if (navigator.platform.indexOf("Win") == 0) {
return [ "DOMMenuItemInactive item2", "DOMMenuItemActive amenu",
"DOMMenuItemInactive amenu", "DOMMenuItemActive item2",
"DOMMenuItemInactive item2", "DOMMenuItemActive item1" ];
- else
- return [ "DOMMenuItemInactive amenu", "DOMMenuItemActive item1" ];
+ }
+ return [ "DOMMenuItemInactive amenu", "DOMMenuItemActive item1" ];
},
test: function() {
if (navigator.platform.indexOf("Win") == 0)
synthesizeKey("VK_DOWN", { });
synthesizeKey("VK_UP", { });
if (navigator.platform.indexOf("Win") == 0)
synthesizeKey("VK_UP", { });
}
@@ -596,22 +596,22 @@ var popupTests = [
}
},
{
// pressing the letter again when the next item is disabled should still
// select the disabled item on Windows, but select the next item on other
// platforms
testname: "menuitem with non accelerator disabled",
events: function() {
- if (navigator.platform.indexOf("Win") == 0)
+ if (navigator.platform.indexOf("Win") == 0) {
return [ "DOMMenuItemInactive submenu", "DOMMenuItemActive other",
"DOMMenuItemInactive other", "DOMMenuItemActive item1" ];
- else
- return [ "DOMMenuItemInactive submenu", "DOMMenuItemActive last",
- "DOMMenuItemInactive last", "DOMMenuItemActive item1" ];
+ }
+ return [ "DOMMenuItemInactive submenu", "DOMMenuItemActive last",
+ "DOMMenuItemInactive last", "DOMMenuItemActive item1" ];
},
test: function() { synthesizeKey("O", { }); synthesizeKey("F", { }); },
result: function(testname) {
checkActive(gMenuPopup, "item1", testname);
}
},
{
// pressing a letter that doesn't correspond to an accelerator nor the
--- a/toolkit/content/widgets/dialog.xml
+++ b/toolkit/content/widgets/dialog.xml
@@ -53,18 +53,17 @@
onget="return this.getAttribute('buttons');"
onset="this._configureButtons(val); return val;"/>
<property name="defaultButton">
<getter>
<![CDATA[
if (this.hasAttribute("defaultButton"))
return this.getAttribute("defaultButton");
- else // default to the accept button
- return "accept";
+ return "accept"; // default to the accept button
]]>
</getter>
<setter>
<![CDATA[
this._setDefaultButton(val);
return val;
]]>
</setter>
--- a/toolkit/content/widgets/tree.xml
+++ b/toolkit/content/widgets/tree.xml
@@ -788,27 +788,25 @@
checkContainers = false;
}
if (checkContainers) {
if (this.changeOpenState(this.currentIndex, false)) {
event.preventDefault();
return;
}
- else {
- var parentIndex = this.view.getParentIndex(this.currentIndex);
- if (parentIndex >= 0) {
- if (cellSelType && !this.view.isSelectable(parentIndex, currentColumn)) {
- return;
- }
- this.view.selection.select(parentIndex);
- this.treeBoxObject.ensureRowIsVisible(parentIndex);
- event.preventDefault();
+ var parentIndex = this.view.getParentIndex(this.currentIndex);
+ if (parentIndex >= 0) {
+ if (cellSelType && !this.view.isSelectable(parentIndex, currentColumn)) {
return;
}
+ this.view.selection.select(parentIndex);
+ this.treeBoxObject.ensureRowIsVisible(parentIndex);
+ event.preventDefault();
+ return;
}
}
if (cellSelType) {
var col = this._getNextColumn(row, true);
if (col) {
this.view.selection.currentColumn = col;
this.treeBoxObject.ensureCellIsVisible(row, col);
@@ -836,35 +834,33 @@
checkContainers = false;
}
if (checkContainers) {
if (this.changeOpenState(row, true)) {
event.preventDefault();
return;
}
- else {
- var c = row + 1;
- var view = this.view;
- if (c < view.rowCount &&
- view.getParentIndex(c) == row) {
- // If already opened, select the first child.
- // The getParentIndex test above ensures that the children
- // are already populated and ready.
- if (cellSelType && !this.view.isSelectable(c , currentColumn)) {
- let col = this._getNextColumn(c, false);
- if (col) {
- this.view.selection.currentColumn = col;
- }
+ var c = row + 1;
+ var view = this.view;
+ if (c < view.rowCount &&
+ view.getParentIndex(c) == row) {
+ // If already opened, select the first child.
+ // The getParentIndex test above ensures that the children
+ // are already populated and ready.
+ if (cellSelType && !this.view.isSelectable(c , currentColumn)) {
+ let col = this._getNextColumn(c, false);
+ if (col) {
+ this.view.selection.currentColumn = col;
}
- this.view.selection.timedSelect(c, this._selectDelay);
- this.treeBoxObject.ensureRowIsVisible(c);
- event.preventDefault();
- return;
}
+ this.view.selection.timedSelect(c, this._selectDelay);
+ this.treeBoxObject.ensureRowIsVisible(c);
+ event.preventDefault();
+ return;
}
}
if (cellSelType) {
let col = this._getNextColumn(row, false);
if (col) {
this.view.selection.currentColumn = col;
this.treeBoxObject.ensureCellIsVisible(row, col);
@@ -1267,21 +1263,20 @@
if (!col) return;
// determine if we have moved the mouse far enough
// to initiate a drag
if (col.mDragGesturing) {
if (Math.abs(aEvent.clientX - col.mStartDragX) < 5 &&
Math.abs(aEvent.clientY - col.mStartDragY) < 5) {
return;
- } else {
- col.mDragGesturing = false;
- col.setAttribute("dragging", "true");
- window.addEventListener("click", col._onDragMouseClick, true);
}
+ col.mDragGesturing = false;
+ col.setAttribute("dragging", "true");
+ window.addEventListener("click", col._onDragMouseClick, true);
}
var pos = {};
var targetCol = col.parentNode.parentNode._getColumnAtX(aEvent.clientX, 0.5, pos);
// bail if we haven't mousemoved to a different column
if (col.mTargetCol == targetCol && col.mTargetDir == pos.value)
return;
--- a/toolkit/identity/RelyingParty.jsm
+++ b/toolkit/identity/RelyingParty.jsm
@@ -105,38 +105,33 @@ IdentityRelyingParty.prototype = {
if (state.email && aRpCaller.loggedInUser === state.email) {
this._notifyLoginStateChanged(aRpCaller.id, state.email);
return aRpCaller.doReady();
} else if (aRpCaller.loggedInUser === null) {
// Generate assertion for existing login
let options = {loggedInUser: state.email, origin: origin};
return this._doLogin(aRpCaller, options);
+ }
+ // A loggedInUser different from state.email has been specified.
+ // Change login identity.
- } else {
- // A loggedInUser different from state.email has been specified.
- // Change login identity.
-
- let options = {loggedInUser: state.email, origin: origin};
- return this._doLogin(aRpCaller, options);
- }
+ let options = {loggedInUser: state.email, origin: origin};
+ return this._doLogin(aRpCaller, options);
// If the user is not logged in, there are two cases:
//
// 1. a logged in email was provided: 'ready'; 'logout'
// 2. not logged in, no email given: 'ready';
- } else {
- if (aRpCaller.loggedInUser) {
- return this._doLogout(aRpCaller, {origin: origin});
-
- } else {
- return aRpCaller.doReady();
- }
}
+ if (aRpCaller.loggedInUser) {
+ return this._doLogout(aRpCaller, {origin: origin});
+ }
+ return aRpCaller.doReady();
},
/**
* A utility for watch() to set state and notify the dom
* on login
*
* Note that this calls _getAssertion
*/
--- a/toolkit/modules/Console.jsm
+++ b/toolkit/modules/Console.jsm
@@ -65,19 +65,17 @@ function fmt(aStr, aMaxLen, aMinLen, aOp
return "_" + aStr.substring(aStr.length - aMaxLen + 1);
}
else if (aOptions && aOptions.truncate == "center") {
let start = aStr.substring(0, (aMaxLen / 2));
let end = aStr.substring((aStr.length - (aMaxLen / 2)) + 1);
return start + "_" + end;
}
- else {
- return aStr.substring(0, aMaxLen - 1) + "_";
- }
+ return aStr.substring(0, aMaxLen - 1) + "_";
}
if (aStr.length < aMinLen) {
let padding = Array(aMinLen - aStr.length + 1).join(" ");
aStr = (aOptions.align === "end") ? padding + aStr : aStr + padding;
}
return aStr;
}
--- a/toolkit/modules/Geometry.jsm
+++ b/toolkit/modules/Geometry.jsm
@@ -61,18 +61,17 @@ Point.prototype = {
}
};
(function() {
function takePointOrArgs(f) {
return function(arg1, arg2) {
if (arg2 === undefined)
return f.call(this, arg1.x, arg1.y);
- else
- return f.call(this, arg1, arg2);
+ return f.call(this, arg1, arg2);
};
}
for (let f of ['add', 'subtract', 'equals', 'set'])
Point.prototype[f] = takePointOrArgs(Point.prototype[f]);
})();
--- a/toolkit/modules/ObjectUtils.jsm
+++ b/toolkit/modules/ObjectUtils.jsm
@@ -65,42 +65,44 @@ this.ObjectUtils = {
function _deepEqual(a, b) {
// The numbering below refers to sections in the CommonJS spec.
// 7.1 All identical values are equivalent, as determined by ===.
if (a === b) {
return true;
// 7.2 If the b value is a Date object, the a value is
// equivalent if it is also a Date object that refers to the same time.
- } else if (instanceOf(a, "Date") && instanceOf(b, "Date")) {
+ }
+ if (instanceOf(a, "Date") && instanceOf(b, "Date")) {
if (isNaN(a.getTime()) && isNaN(b.getTime()))
return true;
return a.getTime() === b.getTime();
// 7.3 If the b value is a RegExp object, the a value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
- } else if (instanceOf(a, "RegExp") && instanceOf(b, "RegExp")) {
+ }
+ if (instanceOf(a, "RegExp") && instanceOf(b, "RegExp")) {
return a.source === b.source &&
a.global === b.global &&
a.multiline === b.multiline &&
a.lastIndex === b.lastIndex &&
a.ignoreCase === b.ignoreCase;
// 7.4 Other pairs that do not both pass typeof value == "object",
// equivalence is determined by ==.
- } else if (typeof a != "object" && typeof b != "object") {
+ }
+ if (typeof a != "object" && typeof b != "object") {
return a == b;
+ }
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
- } else {
- return objEquiv(a, b);
- }
+ return objEquiv(a, b);
}
function instanceOf(object, type) {
return Object.prototype.toString.call(object) == "[object " + type + "]";
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
--- a/toolkit/modules/PrivateBrowsingUtils.jsm
+++ b/toolkit/modules/PrivateBrowsingUtils.jsm
@@ -35,19 +35,18 @@ this.PrivateBrowsingUtils = {
isBrowserPrivate: function(aBrowser) {
let chromeWin = aBrowser.ownerDocument.defaultView;
if (chromeWin.gMultiProcessBrowser) {
// In e10s we have to look at the chrome window's private
// browsing status since the only alternative is to check the
// content window, which is in another process.
return this.isWindowPrivate(chromeWin);
- } else {
- return this.privacyContextFromWindow(aBrowser.contentWindow).usePrivateBrowsing;
}
+ return this.privacyContextFromWindow(aBrowser.contentWindow).usePrivateBrowsing;
},
privacyContextFromWindow: function pbu_privacyContextFromWindow(aWindow) {
return aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsILoadContext);
},
--- a/toolkit/modules/SpatialNavigation.jsm
+++ b/toolkit/modules/SpatialNavigation.jsm
@@ -93,21 +93,20 @@ function _onInputKeyPress (event, callba
// element is the same for some elements, but not all, so we handle the
// ones we want (like the Select element) here:
if (event.target instanceof Ci.nsIDOMHTMLSelectElement &&
event.target.click) {
event.target.click();
event.stopPropagation();
event.preventDefault();
return;
- } else {
- // Leave the action key press to get reported to the DOM as a return
- // keypress.
- return;
}
+ // Leave the action key press to get reported to the DOM as a return
+ // keypress.
+ return;
}
// If it is not using the modifiers it should, return.
if (!event.altKey && PrefObserver['modifierAlt'] ||
!event.shiftKey && PrefObserver['modifierShift'] ||
!event.crtlKey && PrefObserver['modifierCtrl']) {
return;
}
--- a/toolkit/modules/addons/WebRequestUpload.jsm
+++ b/toolkit/modules/addons/WebRequestUpload.jsm
@@ -188,39 +188,37 @@ function parseFormData(stream, channel,
}
try {
let chunk = readChunk();
if (multiplexStream) {
touchedStreams.add(multiplexStream);
return parseMultiPart(chunk);
+ }
+ let contentType;
+ if (/^Content-Type:/i.test(chunk)) {
+ contentType = chunk.replace(/^Content-Type:\s*/i, "");
+ chunk = chunk.slice(chunk.indexOf("\r\n\r\n") + 4);
} else {
- let contentType;
- if (/^Content-Type:/i.test(chunk)) {
- contentType = chunk.replace(/^Content-Type:\s*/i, "");
- chunk = chunk.slice(chunk.indexOf("\r\n\r\n") + 4);
- } else {
- try {
- contentType = channel.getRequestHeader("Content-Type");
- } catch (e) {
- Cu.reportError(e);
- return null;
- }
+ try {
+ contentType = channel.getRequestHeader("Content-Type");
+ } catch (e) {
+ Cu.reportError(e);
+ return null;
}
+ }
- let match = contentType.match(/^(?:multipart\/form-data;\s*boundary=(\S*)|application\/x-www-form-urlencoded\s)/i);
- if (match) {
- let boundary = match[1];
- if (boundary) {
- return parseMultiPart(chunk, boundary);
- } else {
- return parseUrlEncoded(chunk);
- }
+ let match = contentType.match(/^(?:multipart\/form-data;\s*boundary=(\S*)|application\/x-www-form-urlencoded\s)/i);
+ if (match) {
+ let boundary = match[1];
+ if (boundary) {
+ return parseMultiPart(chunk, boundary);
}
+ return parseUrlEncoded(chunk);
}
} finally {
for (let stream of touchedStreams) {
rewind(stream);
}
}
return null;
--- a/toolkit/modules/subprocess/subprocess_worker_win.js
+++ b/toolkit/modules/subprocess/subprocess_worker_win.js
@@ -354,21 +354,20 @@ class Process extends BaseProcess {
secAttr.nLength = win32.SECURITY_ATTRIBUTES.size;
secAttr.bInheritHandle = true;
let pipe = input => {
if (input) {
let handles = win32.createPipe(secAttr, win32.FILE_FLAG_OVERLAPPED);
our_pipes.push(new InputPipe(this, handles[0]));
return handles[1];
- } else {
- let handles = win32.createPipe(secAttr, 0, win32.FILE_FLAG_OVERLAPPED);
- our_pipes.push(new OutputPipe(this, handles[1]));
- return handles[0];
}
+ let handles = win32.createPipe(secAttr, 0, win32.FILE_FLAG_OVERLAPPED);
+ our_pipes.push(new OutputPipe(this, handles[1]));
+ return handles[0];
};
their_pipes[0] = pipe(false);
their_pipes[1] = pipe(true);
if (stderr == "pipe") {
their_pipes[2] = pipe(true);
} else {
--- a/toolkit/mozapps/downloads/content/downloads.js
+++ b/toolkit/mozapps/downloads/content/downloads.js
@@ -827,20 +827,20 @@ function performCommand(aCmd, aItem)
performCommand(aCmd, item);
// Call the callback with no arguments and reset because we're done
if (typeof gPerformAllCallback == "function")
gPerformAllCallback();
gPerformAllCallback = undefined;
return;
- } else {
- while (elm.nodeName != "richlistitem" ||
- elm.getAttribute("type") != "download")
- elm = elm.parentNode;
+ }
+ while (elm.nodeName != "richlistitem" ||
+ elm.getAttribute("type") != "download") {
+ elm = elm.parentNode;
}
gDownloadViewController.doCommand(aCmd, elm);
}
function setSearchboxFocus()
{
gSearchBox.focus();
@@ -1284,22 +1284,21 @@ function getLocalFileFromNativePathOrUrl
// if this is a URL, get the file from that
let ioSvc = Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService);
// XXX it's possible that using a null char-set here is bad
const fileUrl = ioSvc.newURI(aPathOrUrl, null, null).
QueryInterface(Ci.nsIFileURL);
return fileUrl.file.clone().QueryInterface(Ci.nsILocalFile);
- } else {
- // if it's a pathname, create the nsILocalFile directly
- var f = new nsLocalFile(aPathOrUrl);
+ }
+ // if it's a pathname, create the nsILocalFile directly
+ var f = new nsLocalFile(aPathOrUrl);
- return f;
- }
+ return f;
}
/**
* Update the disabled state of the clear list button based on whether or not
* there are items in the list that can potentially be removed.
*/
function updateClearListButton()
{
--- a/toolkit/mozapps/extensions/content/extensions.js
+++ b/toolkit/mozapps/extensions/content/extensions.js
@@ -276,19 +276,18 @@ function getBrowserElement() {
* pane.
*
* This may return null if we can't find the browser chrome window.
*/
function getMainWindowWithPreferencesPane() {
let mainWindow = getMainWindow();
if (mainWindow && "openAdvancedPreferences" in mainWindow) {
return mainWindow;
- } else {
- return null;
}
+ return null;
}
/**
* A wrapper around the HTML5 session history service that allows the browser
* back/forward controls to work within the manager
*/
var HTML5History = {
get index() {
@@ -753,19 +752,18 @@ var gViewController = {
this.loadViewInternal(aViewId, null, state);
this.initialViewSelected = true;
notifyInitialized();
},
get displayedView() {
if (this.viewPort.selectedPanel == this.headeredViews) {
return this.headeredViewsDeck.selectedPanel;
- } else {
- return this.viewPort.selectedPanel;
}
+ return this.viewPort.selectedPanel;
},
set displayedView(view) {
let node = view.node;
if (node.parentNode == this.headeredViewsDeck) {
this.headeredViewsDeck.selectedPanel = node;
this.viewPort.selectedPanel = this.headeredViews;
} else {
@@ -1640,18 +1638,17 @@ function sortElements(aElements, aSortBy
return "pendingUninstall";
if (!addon.isActive &&
(addon.pendingOperations != AddonManager.PENDING_ENABLE &&
addon.pendingOperations != AddonManager.PENDING_INSTALL))
return "disabled";
if (addonType && (addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) &&
addon.userDisabled == AddonManager.STATE_ASK_TO_ACTIVATE)
return "askToActivate";
- else
- return "enabled";
+ return "enabled";
}
return addon[aKey];
}
// aSortFuncs will hold the sorting functions that we'll
// use per element, in the correct order.
var aSortFuncs = [];
--- a/toolkit/mozapps/extensions/internal/AddonRepository.jsm
+++ b/toolkit/mozapps/extensions/internal/AddonRepository.jsm
@@ -1663,19 +1663,18 @@ var AddonDatabase = {
if (!this.connectionPromise) {
return Promise.resolve();
}
this.connectionPromise = null;
if (aSkipFlush) {
return Promise.resolve();
- } else {
- return this.Writer.flush();
}
+ return this.Writer.flush();
},
/**
* Asynchronously deletes the database, shutting down the connection
* first if initialized
*
* @param aCallback
* An optional callback to call once complete
--- a/toolkit/mozapps/extensions/internal/XPIProvider.jsm
+++ b/toolkit/mozapps/extensions/internal/XPIProvider.jsm
@@ -1489,18 +1489,17 @@ var loadManifestFromZipFile = Task.async
finally {
zipReader.close();
}
});
function loadManifestFromFile(aFile, aInstallLocation) {
if (aFile.isFile())
return loadManifestFromZipFile(aFile, aInstallLocation);
- else
- return loadManifestFromDir(aFile, aInstallLocation);
+ return loadManifestFromDir(aFile, aInstallLocation);
}
/**
* A synchronous method for loading an add-on's manifest. This should only ever
* be used during startup or a sync load of the add-ons DB
*/
function syncLoadManifestFromFile(aFile, aInstallLocation) {
let success = undefined;
@@ -2890,20 +2889,18 @@ this.XPIProvider = {
err => {
logger.debug("Notifying XPI shutdown observers");
this._shutdownError = err;
Services.obs.notifyObservers(null, "xpi-provider-shutdown", err);
}
);
return done;
}
- else {
- logger.debug("Notifying XPI shutdown observers");
- Services.obs.notifyObservers(null, "xpi-provider-shutdown", null);
- }
+ logger.debug("Notifying XPI shutdown observers");
+ Services.obs.notifyObservers(null, "xpi-provider-shutdown", null);
return undefined;
},
/**
* Applies any pending theme change to the preferences.
*/
applyThemeChange: function() {
if (!Preferences.get(PREF_DSS_SWITCHPENDING, false))
--- a/toolkit/mozapps/extensions/nsBlocklistService.js
+++ b/toolkit/mozapps/extensions/nsBlocklistService.js
@@ -1168,22 +1168,21 @@ Blocklist.prototype = {
result.push(blockEntry);
},
/* See nsIBlocklistService */
getPluginBlocklistState: function(plugin, appVersion, toolkitVersion) {
if (AppConstants.platform == "android" ||
AppConstants.MOZ_B2G) {
return Ci.nsIBlocklistService.STATE_NOT_BLOCKED;
- } else {
- if (!this._isBlocklistLoaded())
- this._loadBlocklist();
- return this._getPluginBlocklistState(plugin, this._pluginEntries,
- appVersion, toolkitVersion);
}
+ if (!this._isBlocklistLoaded())
+ this._loadBlocklist();
+ return this._getPluginBlocklistState(plugin, this._pluginEntries,
+ appVersion, toolkitVersion);
},
/**
* Private helper to get the blocklist entry for a plugin given a set of
* blocklist entries and versions.
*
* @param plugin
* The nsIPluginTag to get the blocklist state for.
--- a/toolkit/mozapps/extensions/test/browser/browser_plugin_enabled_state_locked.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_plugin_enabled_state_locked.js
@@ -12,21 +12,20 @@ const gIsLinux = ("@mozilla.org/gnome-gc
var gManagerWindow;
var gCategoryUtilities;
var gPluginElement;
function getTestPluginPref() {
let prefix = "plugin.state.";
if (gIsWindows)
- return prefix + "nptest";
- else if (gIsLinux)
- return prefix + "libnptest";
- else
- return prefix + "test";
+ return `${prefix}nptest`;
+ if (gIsLinux)
+ return `${prefix}libnptest`;
+ return `${prefix}test`;
}
registerCleanupFunction(() => {
Services.prefs.unlockPref(getTestPluginPref());
Services.prefs.clearUserPref(getTestPluginPref());
});
function getPlugins() {
--- a/toolkit/mozapps/extensions/test/browser/head.js
+++ b/toolkit/mozapps/extensions/test/browser/head.js
@@ -256,22 +256,20 @@ var get_tooltip_info = Task.async(functi
"Tooltip should always start with the expected name");
if (expectedName.length == tiptext.length) {
return {
name: tiptext,
version: undefined
};
}
- else {
- return {
- name: tiptext.substring(0, expectedName.length),
- version: tiptext.substring(expectedName.length + 1)
- };
- }
+ return {
+ name: tiptext.substring(0, expectedName.length),
+ version: tiptext.substring(expectedName.length + 1)
+ };
});
function get_addon_file_url(aFilename) {
try {
var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
getService(Ci.nsIChromeRegistry);
var fileurl = cr.convertChromeURL(makeURI(CHROMEROOT + "addons/" + aFilename));
return fileurl.QueryInterface(Ci.nsIFileURL);
--- a/toolkit/mozapps/extensions/test/xpcshell/head_addons.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/head_addons.js
@@ -341,20 +341,18 @@ let getIDForManifest = Task.async(functi
let rdfService = AM_Cc["@mozilla.org/rdf/rdf-service;1"].
getService(AM_Ci.nsIRDFService);
let rdfID = ds.GetTarget(rdfService.GetResource("urn:mozilla:install-manifest"),
rdfService.GetResource("http://www.mozilla.org/2004/em-rdf#id"),
true);
return rdfID.QueryInterface(AM_Ci.nsIRDFLiteral).Value;
}
- else {
- let manifest = JSON.parse(data);
- return manifest.applications.gecko.id;
- }
+ let manifest = JSON.parse(data);
+ return manifest.applications.gecko.id;
});
let gUseRealCertChecks = false;
function overrideCertDB(handler) {
// Unregister the real database. This only works because the add-ons manager
// hasn't started up and grabbed the certificate database yet.
let registrar = Components.manager.QueryInterface(AM_Ci.nsIComponentRegistrar);
let factory = registrar.getClassObject(CERTDB_CID, AM_Ci.nsIFactory);
@@ -543,19 +541,17 @@ function do_get_file_hash(aFile, aAlgori
*/
function do_get_addon_root_uri(aProfileDir, aId) {
let path = aProfileDir.clone();
path.append(aId);
if (!path.exists()) {
path.leafName += ".xpi";
return "jar:" + Services.io.newFileURI(path).spec + "!/";
}
- else {
- return Services.io.newFileURI(path).spec;
- }
+ return Services.io.newFileURI(path).spec;
}
function do_get_expected_addon_name(aId) {
if (TEST_UNPACKED)
return aId;
return aId + ".xpi";
}
@@ -1139,32 +1135,30 @@ function writeWebManifestForExtension(aD
fos.init(file,
FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE,
FileUtils.PERMS_FILE, 0);
fos.write(data, data.length);
fos.close();
return dir;
}
- else {
- let file = aDir.clone();
- file.append(aId + ".xpi");
+ let file = aDir.clone();
+ file.append(aId + ".xpi");
- let stream = AM_Cc["@mozilla.org/io/string-input-stream;1"].
- createInstance(AM_Ci.nsIStringInputStream);
- stream.setData(JSON.stringify(aData), -1);
- let zipW = AM_Cc["@mozilla.org/zipwriter;1"].
- createInstance(AM_Ci.nsIZipWriter);
- zipW.open(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE);
- zipW.addEntryStream("manifest.json", 0, AM_Ci.nsIZipWriter.COMPRESSION_NONE,
- stream, false);
- zipW.close();
+ let stream = AM_Cc["@mozilla.org/io/string-input-stream;1"].
+ createInstance(AM_Ci.nsIStringInputStream);
+ stream.setData(JSON.stringify(aData), -1);
+ let zipW = AM_Cc["@mozilla.org/zipwriter;1"].
+ createInstance(AM_Ci.nsIZipWriter);
+ zipW.open(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE);
+ zipW.addEntryStream("manifest.json", 0, AM_Ci.nsIZipWriter.COMPRESSION_NONE,
+ stream, false);
+ zipW.close();
- return file;
- }
+ return file;
}
/**
* Writes an install.rdf manifest into a packed extension using the properties passed
* in a JS object. The objects should contain a property for each property to
* appear in the RDF. The object may contain an array of objects with id,
* minVersion and maxVersion in the targetApplications property to give target
* application compatibility.
@@ -1334,22 +1328,20 @@ function manuallyInstall(aXPIFile, aInst
target.append(aPart);
});
zip.extract(entry, target);
}
zip.close();
return dir;
}
- else {
- let target = aInstallLocation.clone();
- target.append(aID + ".xpi");
- aXPIFile.copyTo(target.parent, target.leafName);
- return target;
- }
+ let target = aInstallLocation.clone();
+ target.append(aID + ".xpi");
+ aXPIFile.copyTo(target.parent, target.leafName);
+ return target;
}
/**
* Manually uninstalls an add-on by removing its files from the install
* location.
*
* @param aInstallLocation
* The nsIFile of the install location to remove from.
--- a/toolkit/mozapps/installer/precompile_cache.js
+++ b/toolkit/mozapps/installer/precompile_cache.js
@@ -58,19 +58,18 @@ function get_modules_under(uri) {
.concat(jar_entries(jarReader, "modules/*.jsm"));
jarReader.close();
return entries;
} else if (uri instanceof Ci.nsIFileURL){
let file = uri.QueryInterface(Ci.nsIFileURL);
return dir_entries(file.file, "components", ".js")
.concat(dir_entries(file.file, "modules", ".js"))
.concat(dir_entries(file.file, "modules", ".jsm"));
- } else {
- throw "Expected a nsIJARURI or nsIFileURL";
}
+ throw new Error("Expected a nsIJARURI or nsIFileURL");
}
function load_modules_under(spec, uri) {
var entries = get_modules_under(uri).sort();
for (let entry of entries) {
try {
dump(spec + entry + "\n");
Cu.import(spec + entry, null);
--- a/toolkit/mozapps/update/content/updates.js
+++ b/toolkit/mozapps/update/content/updates.js
@@ -907,20 +907,18 @@ var gDownloadingPage = {
// We've tried as hard as we could to download a valid update -
// we fell back from a partial patch to a complete patch and even
// then we couldn't validate. Show a validation error with instructions
// on how to manually update.
this.cleanUp();
gUpdates.wiz.goTo("errors");
return;
}
- else {
- // Add this UI as a listener for active downloads
- aus.addDownloadListener(this);
- }
+ // Add this UI as a listener for active downloads
+ aus.addDownloadListener(this);
if (activeUpdate)
this._setUIState(!aus.isDownloading);
}
catch(e) {
LOG("gDownloadingPage", "onPageShow - error: " + e);
}
--- a/toolkit/mozapps/update/nsUpdateService.js
+++ b/toolkit/mozapps/update/nsUpdateService.js
@@ -989,20 +989,19 @@ function shouldUseService() {
ctypes.default_abi,
BOOL,
OSVERSIONINFOEXW.ptr);
let winVer = OSVERSIONINFOEXW();
winVer.dwOSVersionInfoSize = OSVERSIONINFOEXW.size;
if (0 !== GetVersionEx(winVer.address())) {
return winVer.wServicePackMajor >= 3;
- } else {
- Cu.reportError("Unknown failure in GetVersionEX (returned 0)");
- return false;
}
+ Cu.reportError("Unknown failure in GetVersionEX (returned 0)");
+ return false;
} catch (e) {
Cu.reportError("Error getting service pack information. Exception: " + e);
return false;
}
} finally {
kernel32.close();
}
}