bug 1228792 - remove use of array comprehensions r=mossop
authorRobert Helmer <rhelmer@mozilla.com>
Wed, 02 Dec 2015 18:40:59 -0800
changeset 309651 a405a78a5229b02cc3df90c286dd6a4b5390b790
parent 309650 74d91f50bad6807a8bfc7d9f89ee724e2502ec35
child 309652 07267b96720ad327d60b0900d546b785e99d059c
push id5513
push userraliiev@mozilla.com
push dateMon, 25 Jan 2016 13:55:34 +0000
treeherdermozilla-beta@5ee97dd05b5c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmossop
bugs1228792
milestone45.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
bug 1228792 - remove use of array comprehensions r=mossop
toolkit/mozapps/extensions/AddonManager.jsm
toolkit/mozapps/extensions/content/selectAddons.js
toolkit/mozapps/extensions/content/update.js
toolkit/mozapps/extensions/internal/AddonRepository.jsm
toolkit/mozapps/extensions/internal/AddonRepository_SQLiteMigrator.jsm
toolkit/mozapps/extensions/internal/GMPProvider.jsm
toolkit/mozapps/extensions/internal/PluginProvider.jsm
toolkit/mozapps/extensions/internal/XPIProvider.jsm
toolkit/mozapps/extensions/internal/XPIProviderUtils.js
toolkit/mozapps/extensions/test/browser/browser_cancelCompatCheck.js
toolkit/mozapps/extensions/test/xpcshell/head_addons.js
--- a/toolkit/mozapps/extensions/AddonManager.jsm
+++ b/toolkit/mozapps/extensions/AddonManager.jsm
@@ -1288,17 +1288,17 @@ var AddonManagerInternal = {
       let filtered = {};
       for (let prop of NEEDED_PROPS) {
         filtered[prop] = plugin[prop];
       }
       return filtered;
     }
 
     AddonManager.getAddonsByTypes(["plugin"], function(aPlugins) {
-      port.sendAsyncMessage("PluginList", [filterProperties(p) for (p of aPlugins)]);
+      port.sendAsyncMessage("PluginList", aPlugins.map(filterProperties));
     });
   },
 
   /**
    * Notified when a preference we're interested in has changed.
    *
    * @see nsIObserver
    */
@@ -2412,17 +2412,18 @@ var AddonManagerInternal = {
     if (!gStarted)
       throw Components.Exception("AddonManager is not initialized",
                                  Cr.NS_ERROR_NOT_INITIALIZED);
 
     if (!aID || typeof aID != "string")
       throw Components.Exception("aID must be a non-empty string",
                                  Cr.NS_ERROR_INVALID_ARG);
 
-    let promises = [for (p of this.providers) promiseCallProvider(p, "getAddonByID", aID)];
+    let promises = Array.from(this.providers,
+      p => promiseCallProvider(p, "getAddonByID", aID));
     return Promise.all(promises).then(aAddons => {
       return aAddons.find(a => !!a) || null;
     });
   },
 
   /**
    * Asynchronously get an add-on with a specific Sync GUID.
    *
@@ -2477,17 +2478,17 @@ var AddonManagerInternal = {
     if (!gStarted)
       throw Components.Exception("AddonManager is not initialized",
                                  Cr.NS_ERROR_NOT_INITIALIZED);
 
     if (!Array.isArray(aIDs))
       throw Components.Exception("aIDs must be an array",
                                  Cr.NS_ERROR_INVALID_ARG);
 
-    let promises = [AddonManagerInternal.getAddonByID(i) for (i of aIDs)];
+    let promises = aIDs.map(a => AddonManagerInternal.getAddonByID(a));
     return Promise.all(promises);
   },
 
   /**
    * Asynchronously gets add-ons of specific types.
    *
    * @param  aTypes
    *         An optional array of types to retrieve. Each type is a string name
--- a/toolkit/mozapps/extensions/content/selectAddons.js
+++ b/toolkit/mozapps/extensions/content/selectAddons.js
@@ -121,17 +121,17 @@ var gChecking = {
 
   onUpdateFinished: function(aAddon, aError) {
     this._completeCount++;
     this._progress.value = this._completeCount;
 
     if (this._completeCount < this._addonCount)
       return;
 
-    var addons = [gAddons[id] for (id in gAddons)];
+    let addons = Object.values(gAddons);
 
     addons.sort(function(a, b) {
       let orderA = orderForScope(a.addon.scope);
       let orderB = orderForScope(b.addon.scope);
 
       if (orderA != orderB)
         return orderA - orderB;
 
--- a/toolkit/mozapps/extensions/content/update.js
+++ b/toolkit/mozapps/extensions/content/update.js
@@ -126,17 +126,18 @@ var gUpdateWizard = {
     gUpdateWizard.shuttingDown = true;
     // Allow add-ons to continue downloading and installing
     // in the background, though some may require a later restart
     // Pages that are waiting for user input go into the background
     // on cancel
     if (gMismatchPage.waiting) {
       logger.info("Dialog closed in mismatch page");
       if (gUpdateWizard.addonInstalls.size > 0) {
-        gInstallingPage.startInstalls([i for ([, i] of gUpdateWizard.addonInstalls)]);
+        gInstallingPage.startInstalls(
+          Array.from(gUpdateWizard.addonInstalls.values()));
       }
       return true;
     }
 
     // Pages that do asynchronous things will just keep running and check
     // gUpdateWizard.shuttingDown to trigger background behaviour
     if (!gInstallingPage.installing) {
       logger.info("Dialog closed while waiting for updated compatibility information");
@@ -192,28 +193,28 @@ var gVersionInfoPage = {
       // Do the metadata ping, listening for any newly enabled/disabled add-ons.
       yield AddonRepository.repopulateCache(METADATA_TIMEOUT);
       if (gUpdateWizard.shuttingDown) {
         logger.debug("repopulateCache completed after dialog closed");
       }
     }
     // Fetch the add-ons that are still affected by this update,
     // excluding the hotfix add-on.
-    let idlist = [id for (id of gUpdateWizard.affectedAddonIDs)
-                     if (id != AddonManager.hotfixID)];
+    let idlist = Array.from(gUpdateWizard.affectedAddonIDs).filter(
+      a => a.id != AddonManager.hotfixID);
     if (idlist.length < 1) {
       gVersionInfoPage.onAllUpdatesFinished();
       return;
     }
 
     logger.debug("Fetching affected addons " + idlist.toSource());
     let fetchedAddons = yield new Promise((resolve, reject) =>
       AddonManager.getAddonsByIDs(idlist, resolve));
     // We shouldn't get nulls here, but let's be paranoid...
-    gUpdateWizard.addons = [a for (a of fetchedAddons) if (a)];
+    gUpdateWizard.addons = fetchedAddons.filter(a => a);
     if (gUpdateWizard.addons.length < 1) {
       gVersionInfoPage.onAllUpdatesFinished();
       return;
     }
 
     gVersionInfoPage._totalCount = gUpdateWizard.addons.length;
 
     for (let addon of gUpdateWizard.addons) {
@@ -231,35 +232,36 @@ var gVersionInfoPage = {
     AddonManagerPrivate.recordSimpleMeasure("appUpdate_metadata_disabled",
         gUpdateWizard.metadataDisabled);
     // Record 0 for these here in case we exit early; values will be replaced
     // later if we actually upgrade any.
     AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgraded", 0);
     AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgradeFailed", 0);
     AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgradeDeclined", 0);
     // Filter out any add-ons that are now enabled.
-    logger.debug("VersionInfo updates finished: found " +
-         [addon.id + ":" + addon.appDisabled for (addon of gUpdateWizard.addons)].toSource());
+    let addonList = gUpdateWizard.addons.map(a => a.id + ":" + a.appDisabled);
+    logger.debug("VersionInfo updates finished: found " + addonList.toSource());
     let filteredAddons = [];
     for (let a of gUpdateWizard.addons) {
       if (a.appDisabled) {
         logger.debug("Continuing with add-on " + a.id);
         filteredAddons.push(a);
       }
       else if (gUpdateWizard.addonInstalls.has(a.id)) {
         gUpdateWizard.addonInstalls.get(a.id).cancel();
         gUpdateWizard.addonInstalls.delete(a.id);
       }
     }
     gUpdateWizard.addons = filteredAddons;
 
     if (gUpdateWizard.shuttingDown) {
       // jump directly to updating auto-update add-ons in the background
       if (gUpdateWizard.addonInstalls.size > 0) {
-        gInstallingPage.startInstalls([i for ([, i] of gUpdateWizard.addonInstalls)]);
+        let installs = Array.from(gUpdateWizard.addonInstalls.values());
+        gInstallingPage.startInstalls(installs);
       }
       return;
     }
 
     if (filteredAddons.length > 0) {
       if (!gUpdateWizard.xpinstallEnabled && gUpdateWizard.xpinstallLocked) {
         document.documentElement.currentPage = document.getElementById("adminDisabled");
         return;
@@ -475,18 +477,18 @@ var gInstallingPage = {
 
   // Initialize fields we need for installing and tracking progress,
   // and start iterating through the installations
   startInstalls: function(aInstallList) {
     if (!gUpdateWizard.xpinstallEnabled) {
       return;
     }
 
-    logger.debug("Start installs for "
-                 + [i.existingAddon.id for (i of aInstallList)].toSource());
+    let installs = Array.from(aInstallList).map(a => a.existingAddon.id);
+    logger.debug("Start installs for " + installs.toSource());
     this._errors = [];
     this._installs = aInstallList;
     this._installing = true;
     this.startNextInstall();
   },
 
   onPageShow: function()
   {
--- a/toolkit/mozapps/extensions/internal/AddonRepository.jsm
+++ b/toolkit/mozapps/extensions/internal/AddonRepository.jsm
@@ -619,25 +619,25 @@ this.AddonRepository = {
     );
   },
 
   _repopulateCacheInternal: Task.async(function*(aSendPerformance, aTimeout) {
     let allAddons = yield new Promise((resolve, reject) =>
       AddonManager.getAllAddons(resolve));
 
     // Filter the hotfix out of our list of add-ons
-    allAddons = [a for (a of allAddons) if (a.id != AddonManager.hotfixID)];
+    allAddons = allAddons.filter(a => a.id != AddonManager.hotfixID);
 
     // Completely remove cache if caching is not enabled
     if (!this.cacheEnabled) {
       logger.debug("Clearing cache because it is disabled");
       return this._clearCache();
     }
 
-    let ids = [a.id for (a of allAddons)];
+    let ids = allAddons.map(a => a.id);
     logger.debug("Repopulate add-on cache with " + ids.toSource());
 
     let addonsToCache = yield new Promise((resolve, reject) =>
       getAddonsToCache(ids, resolve));
 
     // Completely remove cache if there are no add-ons to cache
     if (addonsToCache.length == 0) {
       logger.debug("Clearing cache because 0 add-ons were requested");
--- a/toolkit/mozapps/extensions/internal/AddonRepository_SQLiteMigrator.jsm
+++ b/toolkit/mozapps/extensions/internal/AddonRepository_SQLiteMigrator.jsm
@@ -55,17 +55,17 @@ this.AddonRepository_SQLiteMigrator = {
       aCallback([]);
       return false;
     }
 
     logger.debug("Importing addon repository from previous " + FILE_DATABASE + " storage.");
 
     this._retrieveStoredData((results) => {
       this._closeConnection();
-      let resultArray = [addon for ([,addon] of Iterator(results))];
+      let resultArray = Object.values(results);
       logger.debug(resultArray.length + " addons imported.")
       aCallback(resultArray);
     });
 
     return true;
   },
 
   /**
--- a/toolkit/mozapps/extensions/internal/GMPProvider.jsm
+++ b/toolkit/mozapps/extensions/internal/GMPProvider.jsm
@@ -654,18 +654,20 @@ var GMPProvider = {
 
   getAddonsByTypes: function(aTypes, aCallback) {
     if (!this.isEnabled ||
         (aTypes && aTypes.indexOf("plugin") < 0)) {
       aCallback([]);
       return;
     }
 
-    let results = [p.wrapper for ([id, p] of this._plugins)
-                    if (!GMPUtils.isPluginHidden(p))];
+    let results = Array.from(this._plugins.values())
+      .filter(p => !GMPUtils.isPluginHidden(p))
+      .map(p => p.wrapper);
+
     aCallback(results);
   },
 
   get isEnabled() {
     return GMPPrefs.get(GMPPrefs.KEY_PROVIDER_ENABLED, false);
   },
 
   generateFullDescription: function(aPlugin) {
--- a/toolkit/mozapps/extensions/internal/PluginProvider.jsm
+++ b/toolkit/mozapps/extensions/internal/PluginProvider.jsm
@@ -34,17 +34,18 @@ function getIDHashForString(aStr) {
   hasher.init(Ci.nsICryptoHash.MD5);
   let stringStream = Cc["@mozilla.org/io/string-input-stream;1"].
                      createInstance(Ci.nsIStringInputStream);
                      stringStream.data = aStr ? aStr : "null";
   hasher.updateFromStream(stringStream, -1);
 
   // convert the binary hash data to a hex string.
   let binary = hasher.finish(false);
-  let hash = [toHexString(binary.charCodeAt(i)) for (i in binary)].join("").toLowerCase();
+  let hash = Array.from(binary, c => toHexString(c.charCodeAt(0)));
+  hash = hash.join("").toLowerCase();
   return "{" + hash.substr(0, 8) + "-" +
                hash.substr(8, 4) + "-" +
                hash.substr(12, 4) + "-" +
                hash.substr(16, 4) + "-" +
                hash.substr(20) + "}";
 }
 
 var PluginProvider = {
--- a/toolkit/mozapps/extensions/internal/XPIProvider.jsm
+++ b/toolkit/mozapps/extensions/internal/XPIProvider.jsm
@@ -331,23 +331,22 @@ LAZY_OBJECTS.forEach(name => {
 
 // Behaves like Promise.all except waits for all promises to resolve/reject
 // before resolving/rejecting itself
 function waitForAllPromises(promises) {
   return new Promise((resolve, reject) => {
     let shouldReject = false;
     let rejectValue = null;
 
-    let newPromises = [
-      for (p of promises)
-        p.catch(value => {
-          shouldReject = true;
-          rejectValue = value;
-        })
-    ]
+    let newPromises = promises.map(
+      p => p.catch(value => {
+        shouldReject = true;
+        rejectValue = value;
+      })
+    );
     Promise.all(newPromises)
            .then((results) => shouldReject ? reject(rejectValue) : resolve(results));
   });
 }
 
 function findMatchingStaticBlocklistItem(aAddon) {
   for (let item of STATIC_BLOCKLIST_PATTERNS) {
     if ("creator" in item && typeof item.creator == "string") {
@@ -359,17 +358,17 @@ function findMatchingStaticBlocklistItem
   }
   return null;
 }
 
 /**
  * Converts an iterable of addon objects into a map with the add-on's ID as key.
  */
 function addonMap(addons) {
-  return new Map([for (a of addons) [a.id, a]]);
+  return new Map(addons.map(a => [a.id, a]));
 }
 
 /**
  * Sets permissions on a file
  *
  * @param  aFile
  *         The file or directory to operate on.
  * @param  aPermissions
@@ -2941,17 +2940,18 @@ this.XPIProvider = {
     let addonList = yield ProductAddonChecker.getProductAddonList(url);
 
     // If there was no list then do nothing.
     if (!addonList) {
       logger.info("No system add-ons list was returned.");
       return systemAddonLocation.cleanDirectories();
     }
 
-    addonList = new Map([for (spec of addonList) [spec.id, { spec, path: null, addon: null }]]);
+    addonList = new Map(
+      addonList.map(spec => [spec.id, { spec, path: null, addon: null }]));
 
     let getAddonsInLocation = (location) => {
       return new Promise(resolve => {
         XPIDatabase.getAddonsInLocation(location, resolve);
       });
     };
 
     let setMatches = (wanted, existing) => {
@@ -3014,17 +3014,17 @@ this.XPIProvider = {
           item.path = yield ProductAddonChecker.downloadAddon(item.spec);
         }
         item.addon = yield loadManifestFromFile(nsIFile(item.path), systemAddonLocation);
       }
       catch (e) {
         logger.error(`Failed to download system add-on ${item.spec.id}`, e);
       }
     });
-    yield Promise.all([for (item of addonList.values()) downloadAddon(item)]);
+    yield Promise.all(Array.from(addonList.values()).map(downloadAddon));
 
     // The download promises all resolve regardless, now check if they all
     // succeeded
     let validateAddon = (item) => {
       if (item.spec.id != item.addon.id) {
         logger.warn(`Downloaded system add-on expected to be ${item.spec.id} but was ${item.addon.id}.`);
         return false;
       }
@@ -3043,17 +3043,18 @@ this.XPIProvider = {
     try {
       if (!Array.from(addonList.values()).every(item => item.path && item.addon && validateAddon(item))) {
         throw new Error("Rejecting updated system add-on set that either could not " +
                         "be downloaded or contained unusable add-ons.");
       }
 
       // Install into the install location
       logger.info("Installing new system add-on set");
-      yield systemAddonLocation.installAddonSet([for (item of addonList.values()) item.addon]);
+      yield systemAddonLocation.installAddonSet(Array.from(addonList.values())
+        .map(a => a.addon));
 
       // Bug 1204156: Switch to the new system add-ons without requiring a restart
     }
     finally {
       // Delete the temporary files
       logger.info("Deleting temporary files");
       for (let item of addonList.values()) {
         // If this item downloaded delete the temporary file.
@@ -3600,28 +3601,28 @@ this.XPIProvider = {
     // no need to update the database.
     let dbFile = FileUtils.getFile(KEY_PROFILEDIR, [FILE_DATABASE], true);
     if (!dbFile.exists() && haveAnyAddons) {
       updateReasons.push("needNewDatabase");
     }
 
     // XXX This will go away when we fold bootstrappedAddons into XPIStates.
     if (updateReasons.length == 0) {
-      let bootstrapDescriptors = new Set([for (b of Object.keys(this.bootstrappedAddons))
-                                          this.bootstrappedAddons[b].descriptor]);
+      let bootstrapDescriptors = new Set(Object.keys(this.bootstrappedAddons)
+        .map(b => this.bootstrappedAddons[b].descriptor));
 
       for (let location of XPIStates.db.values()) {
         for (let state of location.values()) {
           bootstrapDescriptors.delete(state.descriptor);
         }
       }
 
       if (bootstrapDescriptors.size > 0) {
         logger.warn("Bootstrap state is invalid (missing add-ons: "
-            + [for (b of bootstrapDescriptors) b] + ")");
+            + Array.from(bootstrapDescriptors).join(", ") + ")");
         updateReasons.push("missingBootstrapAddon");
       }
     }
 
     // Catch and log any errors during the main startup
     try {
       let extensionListChanged = false;
       // If the database needs to be updated then open it and then update it
@@ -4885,17 +4886,18 @@ this.XPIProvider = {
 };
 
 function getHashStringForCrypto(aCrypto) {
   // return the two-digit hexadecimal code for a byte
   let toHexString = charCode => ("0" + charCode.toString(16)).slice(-2);
 
   // convert the binary hash data to a hex string.
   let binary = aCrypto.finish(false);
-  return [toHexString(binary.charCodeAt(i)) for (i in binary)].join("").toLowerCase()
+  let hash = Array.from(binary, c => toHexString(c.charCodeAt(0)))
+  return hash.join("").toLowerCase();
 }
 
 /**
  * Instantiates an AddonInstall.
  *
  * @param  aInstallLocation
  *         The install location the add-on will be installed into
  * @param  aUrl
@@ -7938,17 +7940,17 @@ Object.assign(SystemAddonInstallLocation
       catch (e) {
         logger.error(`Failed to copy ${addon.id} from ${addon._sourceBundle.path} to ${target}.`, e);
         throw e;
       }
       addon._sourceBundle = new nsIFile(target);
     });
 
     try {
-      yield waitForAllPromises([for (addon of aAddons) copyAddon(addon)]);
+      yield waitForAllPromises(aAddons.map(copyAddon));
     }
     catch (e) {
       try {
         yield OS.File.removeDir(newDir.path, { ignorePermissions: true });
       }
       catch (e) {
         logger.warn(`Failed to remove new system add-on directory ${newDir.path}.`, e);
       }
--- a/toolkit/mozapps/extensions/internal/XPIProviderUtils.js
+++ b/toolkit/mozapps/extensions/internal/XPIProviderUtils.js
@@ -409,17 +409,17 @@ function _findAddon(addonDB, aFilter) {
   }
   return null;
 }
 
 /**
  * Internal interface to get a filtered list of addons from a loaded addonDB
  */
 function _filterDB(addonDB, aFilter) {
-  return [for (addon of addonDB.values()) if (aFilter(addon)) addon];
+  return Array.from(addonDB.values()).filter(aFilter);
 }
 
 this.XPIDatabase = {
   // true if the database connection has been opened
   initialized: false,
   // The database file
   jsonFile: FileUtils.getFile(KEY_PROFILEDIR, [FILE_JSON_DB], true),
   // Migration data loaded from an old version of the database.
--- a/toolkit/mozapps/extensions/test/browser/browser_cancelCompatCheck.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_cancelCompatCheck.js
@@ -215,17 +215,17 @@ var inactiveAddonIds = [
   ao6.id,
   ao7.id,
   ao8.id,
   ao9.id
 ];
 
 // Make sure the addons in the list are not installed
 function* check_addons_uninstalled(aAddonList) {
-  let foundList = yield promise_addons_by_ids([addon.id for (addon of aAddonList)]);
+  let foundList = yield promise_addons_by_ids(aAddonList.map(a => a.id));
   for (let i = 0; i < aAddonList.length; i++) {
     ok(!foundList[i], "Addon " + aAddonList[i].id + " is not installed");
   }
   info("Add-on uninstall check complete");
   yield true;
 }
 
 // Test what happens when the user cancels during AddonRepository.repopulateCache()
--- a/toolkit/mozapps/extensions/test/xpcshell/head_addons.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/head_addons.js
@@ -368,17 +368,18 @@ function do_get_file_hash(aFile, aAlgori
             createInstance(AM_Ci.nsIFileInputStream);
   fis.init(aFile, -1, -1, false);
   crypto.updateFromStream(fis, aFile.fileSize);
 
   // return the two-digit hexadecimal code for a byte
   let toHexString = charCode => ("0" + charCode.toString(16)).slice(-2);
 
   let binary = crypto.finish(false);
-  return aAlgorithm + ":" + [toHexString(binary.charCodeAt(i)) for (i in binary)].join("")
+  let hash = Array.from(binary, c => toHexString(c.charCodeAt(0)));
+  return aAlgorithm + ":" + hash.join("");
 }
 
 /**
  * Returns an extension uri spec
  *
  * @param  aProfileDir
  *         The extension install directory
  * @return a uri spec pointing to the root of the extension