Bug 1365068 - import with destructuring, switch to shorthand function declarations and use array.includes. r=mattn draft
authorJonathan Guillotte-Blouin <jguillotteblouin@mozilla.com>
Tue, 16 May 2017 18:23:56 -0700
changeset 580819 17b2e2b5c54410a203c5dd5351dc2edf6d544a9a
parent 580790 5eeb70750e09166873d2af45fb7e0ef7467c24a4
child 629389 49f2baa2808db3643d080a4d4ada7c98ea560bc6
push id59666
push userbmo:jguillotteblouin@mozilla.com
push dateThu, 18 May 2017 23:39:50 +0000
reviewersmattn
bugs1365068
milestone55.0a1
Bug 1365068 - import with destructuring, switch to shorthand function declarations and use array.includes. r=mattn MozReview-Commit-ID: IfmePvN8WnA
toolkit/components/satchel/AutoCompletePopup.jsm
toolkit/components/satchel/FormHistory.jsm
toolkit/components/satchel/FormHistoryStartup.js
toolkit/components/satchel/formSubmitListener.js
toolkit/components/satchel/nsFormAutoComplete.js
toolkit/components/satchel/nsFormAutoCompleteResult.jsm
toolkit/components/satchel/nsInputListAutoComplete.js
--- a/toolkit/components/satchel/AutoCompletePopup.jsm
+++ b/toolkit/components/satchel/AutoCompletePopup.jsm
@@ -1,17 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
 
 this.EXPORTED_SYMBOLS = [ "AutoCompletePopup" ];
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 
 // AutoCompleteResultView is an abstraction around a list of results
 // we got back up from browser-content.js. It implements enough of
--- a/toolkit/components/satchel/FormHistory.jsm
+++ b/toolkit/components/satchel/FormHistory.jsm
@@ -80,23 +80,21 @@
  * For search and getAutoCompeteResults, result is an object containing the desired
  * properties. For count, result is the integer count. For, update, handleResult is
  * not called. For handleCompletion, reason is either 0 if successful or 1 if
  * an error occurred.
  */
 
 this.EXPORTED_SYMBOLS = ["FormHistory"];
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cr = Components.results;
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
 
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/AppConstants.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/AppConstants.jsm");
 
 XPCOMUtils.defineLazyServiceGetter(this, "uuidService",
                                    "@mozilla.org/uuid-generator;1",
                                    "nsIUUIDGenerator");
 
 const DB_SCHEMA_VERSION = 4;
 const DAY_IN_MS  = 86400000; // 1 day in milliseconds
 const MAX_SEARCH_TOKENS = 10;
@@ -209,37 +207,37 @@ const searchFilters = [
 function validateOpData(aData, aDataType) {
   let thisValidFields = validFields;
   // A special case to update the GUID - in this case there can be a 'newGuid'
   // field and of the normally valid fields, only 'guid' is accepted.
   if (aDataType == "Update" && "newGuid" in aData) {
     thisValidFields = ["guid", "newGuid"];
   }
   for (let field in aData) {
-    if (field != "op" && thisValidFields.indexOf(field) == -1) {
+    if (field != "op" && !thisValidFields.includes(field)) {
       throw Components.Exception(
         aDataType + " query contains an unrecognized field: " + field,
         Cr.NS_ERROR_ILLEGAL_VALUE);
     }
   }
   return aData;
 }
 
 function validateSearchData(aData, aDataType) {
   for (let field in aData) {
-    if (field != "op" && validFields.indexOf(field) == -1 && searchFilters.indexOf(field) == -1) {
+    if (field != "op" && !validFields.includes(field) && !searchFilters.includes(field)) {
       throw Components.Exception(
         aDataType + " query contains an unrecognized field: " + field,
         Cr.NS_ERROR_ILLEGAL_VALUE);
     }
   }
 }
 
 function makeQueryPredicates(aQueryData, delimiter = " AND ") {
-  return Object.keys(aQueryData).map(function(field) {
+  return Object.keys(aQueryData).map(field => {
     switch (field) {
       case "firstUsedStart": {
         return "firstUsed >= :" + field;
       }
       case "firstUsedEnd": {
         return "firstUsed <= :" + field;
       }
       case "lastUsedStart": {
@@ -527,17 +525,17 @@ function dbMigrate(oldVersion) {
   log("DB migration completed.");
 }
 
 var Migrators = {
   /*
    * Updates the DB schema to v3 (bug 506402).
    * Adds deleted form history table.
    */
-  dbMigrateToVersion4: function dbMigrateToVersion4() {
+  dbMigrateToVersion4() {
     if (!_dbConnection.tableExists("moz_deleted_formhistory")) {
       let table = dbSchema.tables["moz_deleted_formhistory"];
       let tSQL = Object.keys(table).map(col => [col, table[col]].join(" ")).join(", ");
       _dbConnection.createTable("moz_deleted_formhistory", tSQL);
     }
   }
 };
 
@@ -637,17 +635,17 @@ function updateFormHistoryWrite(aChanges
   for (let change of aChanges) {
     let operation = change.op;
     delete change.op;
     let stmt;
     switch (operation) {
       case "remove":
         log("Remove from form history  " + change);
         let delStmt = makeMoveToDeletedStatement(change.guid, now, change, bindingArrays);
-        if (delStmt && stmts.indexOf(delStmt) == -1) {
+        if (delStmt && !stmts.includes(delStmt)) {
           stmts.push(delStmt);
         }
         if ("timeDeleted" in change) {
           delete change.timeDeleted;
         }
         stmt = makeRemoveStatement(change, bindingArrays);
         notifications.push([ "formhistory-remove", change.guid ]);
         break;
@@ -683,17 +681,17 @@ function updateFormHistoryWrite(aChanges
         break;
       default:
         // We should've already guaranteed that change.op is one of the above
         throw Components.Exception("Invalid operation " + operation,
                                    Cr.NS_ERROR_ILLEGAL_VALUE);
     }
 
     // As identical statements are reused, only add statements if they aren't already present.
-    if (stmt && stmts.indexOf(stmt) == -1) {
+    if (stmt && !stmts.includes(stmt)) {
       stmts.push(stmt);
     }
   }
 
   for (let stmt of stmts) {
     stmt.bindParameters(bindingArrays.get(stmt));
   }
 
@@ -777,17 +775,17 @@ function expireOldEntriesVacuum(aExpireT
   });
 }
 
 this.FormHistory = {
   get enabled() {
     return Prefs.enabled;
   },
 
-  search: function formHistorySearch(aSelectTerms, aSearchData, aCallbacks) {
+  search(aSelectTerms, aSearchData, aCallbacks) {
     // if no terms selected, select everything
     if (!aSelectTerms) {
       aSelectTerms = validFields;
     }
     validateSearchData(aSearchData, "Search");
 
     let stmt = makeSearchStatement(aSearchData, aSelectTerms);
 
@@ -806,55 +804,55 @@ this.FormHistory = {
       },
 
       handleError(aError) {
         if (aCallbacks && aCallbacks.handleError) {
           aCallbacks.handleError(aError);
         }
       },
 
-      handleCompletion: function searchCompletionHandler(aReason) {
+      handleCompletion(aReason) {
         if (aCallbacks && aCallbacks.handleCompletion) {
           aCallbacks.handleCompletion(aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED ? 0 : 1);
         }
       }
     };
 
     stmt.executeAsync(handlers);
   },
 
-  count: function formHistoryCount(aSearchData, aCallbacks) {
+  count(aSearchData, aCallbacks) {
     validateSearchData(aSearchData, "Count");
     let stmt = makeCountStatement(aSearchData);
     let handlers = {
-      handleResult: function countResultHandler(aResultSet) {
+      handleResult(aResultSet) {
         let row = aResultSet.getNextRow();
         let count = row.getResultByName("numEntries");
         if (aCallbacks && aCallbacks.handleResult) {
           aCallbacks.handleResult(count);
         }
       },
 
       handleError(aError) {
         if (aCallbacks && aCallbacks.handleError) {
           aCallbacks.handleError(aError);
         }
       },
 
-      handleCompletion: function searchCompletionHandler(aReason) {
+      handleCompletion(aReason) {
         if (aCallbacks && aCallbacks.handleCompletion) {
           aCallbacks.handleCompletion(aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED ? 0 : 1);
         }
       }
     };
 
     stmt.executeAsync(handlers);
   },
 
-  update: function formHistoryUpdate(aChanges, aCallbacks) {
+  update(aChanges, aCallbacks) {
     // Used to keep track of how many searches have been started. When that number
     // are finished, updateFormHistoryWrite can be called.
     let numSearches = 0;
     let completedSearches = 0;
     let searchFailed = false;
 
     function validIdentifier(change) {
       // The identifier is only valid if one of either the guid or the (fieldname/value) are set (so an X-OR)
@@ -972,17 +970,17 @@ this.FormHistory = {
     }
 
     if (numSearches == 0) {
       // We don't have to wait for any statements to return.
       updateFormHistoryWrite(aChanges, aCallbacks);
     }
   },
 
-  getAutoCompleteResults: function getAutoCompleteResults(searchString, params, aCallbacks) {
+  getAutoCompleteResults(searchString, params, aCallbacks) {
     // only do substring matching when the search string contains more than one character
     let searchTokens;
     let where = ""
     let boundaryCalc = "";
     if (searchString.length > 1) {
         searchTokens = searchString.split(/\s+/);
 
         // build up the word boundary and prefix match bonus calculation
@@ -1096,21 +1094,21 @@ this.FormHistory = {
   get _supportsDeletedTable() {
     return supportsDeletedTable;
   },
   set _supportsDeletedTable(val) {
     supportsDeletedTable = val;
   },
 
   // The remaining methods are called by FormHistoryStartup.js
-  updatePrefs: function updatePrefs() {
+  updatePrefs() {
     Prefs.initialized = false;
   },
 
-  expireOldEntries: function expireOldEntries() {
+  expireOldEntries() {
     log("expireOldEntries");
 
     // Determine how many days of history we're supposed to keep.
     // Calculate expireTime in microseconds
     let expireTime = (Date.now() - Prefs.expireDays * DAY_IN_MS) * 1000;
 
     sendNotification("formhistory-beforeexpireoldentries", expireTime);
 
@@ -1119,13 +1117,13 @@ this.FormHistory = {
         expireOldEntriesDeletion(expireTime, aBeginningCount);
       },
       handleError(aError) {
         log("expireStartCountFailure");
       }
     });
   },
 
-  shutdown: function shutdown() { dbClose(true); }
+  shutdown() { dbClose(true); }
 };
 
 // Prevent add-ons from redefining this API
 Object.freeze(FormHistory);
--- a/toolkit/components/satchel/FormHistoryStartup.js
+++ b/toolkit/components/satchel/FormHistoryStartup.js
@@ -1,14 +1,13 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
 
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 Components.utils.import("resource://gre/modules/Services.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "FormHistory",
                                   "resource://gre/modules/FormHistory.jsm");
 
 function FormHistoryStartup() { }
@@ -69,23 +68,21 @@ FormHistoryStartup.prototype = {
       manager.addMessageListener("FormHistory:RemoveEntry", this);
     }
   },
 
   receiveMessage(message) {
     switch (message.name) {
       case "FormHistory:FormSubmitEntries": {
         let entries = message.data;
-        let changes = entries.map(function(entry) {
-          return {
-            op: "bump",
-            fieldname: entry.name,
-            value: entry.value,
-          }
-        });
+        let changes = entries.map(entry => ({
+          op: "bump",
+          fieldname: entry.name,
+          value: entry.value,
+        }));
 
         FormHistory.update(changes);
         break;
       }
 
       case "FormHistory:AutoCompleteSearchAsync": {
         let { id, searchString, params } = message.data;
 
--- a/toolkit/components/satchel/formSubmitListener.js
+++ b/toolkit/components/satchel/formSubmitListener.js
@@ -1,18 +1,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* eslint-env mozilla/frame-script */
 
 (function() {
 
-var Cc = Components.classes;
-var Ci = Components.interfaces;
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
 
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 Components.utils.import("resource://gre/modules/Services.jsm");
 Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
 
 var satchelFormListener = {
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIFormSubmitObserver,
                                          Ci.nsIObserver,
--- a/toolkit/components/satchel/nsFormAutoComplete.js
+++ b/toolkit/components/satchel/nsFormAutoComplete.js
@@ -1,16 +1,16 @@
 /* vim: set ts=4 sts=4 sw=4 et tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
-const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "BrowserUtils", "resource://gre/modules/BrowserUtils.jsm");
 
 function isAutocompleteDisabled(aField) {
   if (aField.autocomplete !== "") {
@@ -326,17 +326,17 @@ FormAutoComplete.prototype = {
 
     this.log("AutoCompleteSearch invoked. Search is: " + aUntrimmedSearchString);
     let searchString = aUntrimmedSearchString.trim().toLowerCase();
 
     // reuse previous results if:
     // a) length greater than one character (others searches are special cases) AND
     // b) the the new results will be a subset of the previous results
     if (aPreviousResult && aPreviousResult.searchString.trim().length > 1 &&
-      searchString.indexOf(aPreviousResult.searchString.trim().toLowerCase()) >= 0) {
+      searchString.includes(aPreviousResult.searchString.trim().toLowerCase())) {
       this.log("Using previous autocomplete result");
       let result = aPreviousResult;
       let wrappedResult = result.wrappedJSObject;
       wrappedResult.searchString = aUntrimmedSearchString;
 
       // Leaky abstraction alert: it would be great to be able to split
       // this code between nsInputListAutoComplete and here but because of
       // the way we abuse the formfill autocomplete API in e10s, we have
@@ -371,17 +371,17 @@ FormAutoComplete.prototype = {
       // We have a list of results for a shorter search string, so just
       // filter them further based on the new search string and add to a new array.
       let entries = wrappedResult.entries;
       let filteredEntries = [];
       for (let i = 0; i < entries.length; i++) {
         let entry = entries[i];
         // Remove results that do not contain the token
         // XXX bug 394604 -- .toLowerCase can be wrong for some intl chars
-        if (searchTokens.some(tok => entry.textLowerCase.indexOf(tok) < 0)) {
+        if (searchTokens.some(tok => !entry.textLowerCase.includes(tok))) {
           continue;
         }
         this._calculateScore(entry, searchString, searchTokens);
         this.log("Reusing autocomplete entry '" + entry.text +
                  "' (" + entry.frecency + " / " + entry.totalScore + ")");
         filteredEntries.push(entry);
       }
       filteredEntries.sort(sortBytotalScore);
@@ -413,17 +413,17 @@ FormAutoComplete.prototype = {
       // Start with an empty list.
       let result = aDatalistResult ?
         new FormAutoCompleteResult(client, [], aInputName, aUntrimmedSearchString, null) :
         emptyResult;
 
       let processEntry = (aEntries) => {
         if (aField && aField.maxLength > -1) {
           result.entries =
-            aEntries.filter(function(el) { return el.text.length <= aField.maxLength; });
+            aEntries.filter(el => el.text.length <= aField.maxLength);
         } else {
           result.entries = aEntries;
         }
 
         if (aDatalistResult && aDatalistResult.matchCount > 0) {
           result = this.mergeResults(result, aDatalistResult);
         }
 
@@ -511,17 +511,17 @@ FormAutoComplete.prototype = {
    *
    * Returns: an int
    */
   _calculateScore(entry, aSearchString, searchTokens) {
     let boundaryCalc = 0;
     // for each word, calculate word boundary weights
     for (let token of searchTokens) {
       boundaryCalc += (entry.textLowerCase.indexOf(token) == 0);
-      boundaryCalc += (entry.textLowerCase.indexOf(" " + token) >= 0);
+      boundaryCalc += (entry.textLowerCase.includes(" " + token));
     }
     boundaryCalc = boundaryCalc * this._boundaryWeight;
     // now add more weight if we have a traditional prefix match and
     // multiply boundary bonuses by boundary weight
     boundaryCalc += this._prefixWeight * (entry.textLowerCase.indexOf(aSearchString) == 0);
     entry.totalScore = Math.round(entry.frecency * Math.max(1, boundaryCalc));
   }
 
--- a/toolkit/components/satchel/nsFormAutoCompleteResult.jsm
+++ b/toolkit/components/satchel/nsFormAutoCompleteResult.jsm
@@ -1,16 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 this.EXPORTED_SYMBOLS = [ "FormAutoCompleteResult" ];
 
-const Ci = Components.interfaces;
-const Cr = Components.results;
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
 
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 this.FormAutoCompleteResult =
  function FormAutoCompleteResult(searchString,
                                  searchResult,
                                  defaultIndex,
                                  errorDescription,
--- a/toolkit/components/satchel/nsInputListAutoComplete.js
+++ b/toolkit/components/satchel/nsInputListAutoComplete.js
@@ -1,13 +1,13 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-const Ci = Components.interfaces;
+const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
 
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 Components.utils.import("resource://gre/modules/Services.jsm");
 Components.utils.import("resource://gre/modules/nsFormAutoCompleteResult.jsm");
 
 function InputListAutoComplete() {}
 
 InputListAutoComplete.prototype = {