diff options
author | Alex Lam S.L <alexlamsl@gmail.com> | 2018-04-03 15:15:01 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-04-03 15:15:01 +0800 |
commit | 81603ecd156f494a6b0c02655c5361152711300d (patch) | |
tree | fe288905905789ee165daee0fcdbef5f48f84cbb /lib/utils.js | |
parent | e67553fa550ad355aa1946b5da5051434259a6ba (diff) | |
download | tracifyjs-81603ecd156f494a6b0c02655c5361152711300d.tar.gz tracifyjs-81603ecd156f494a6b0c02655c5361152711300d.zip |
improve performance through `makePredicate()` (#3048)
Diffstat (limited to 'lib/utils.js')
-rw-r--r-- | lib/utils.js | 53 |
1 files changed, 8 insertions, 45 deletions
diff --git a/lib/utils.js b/lib/utils.js index 9121fa93..7e99f0d9 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -145,7 +145,7 @@ var MAP = (function(){ } return is_last; }; - if (a instanceof Array) { + if (Array.isArray(a)) { if (backwards) { for (i = a.length; --i >= 0;) if (doit()) break; ret.reverse(); @@ -210,51 +210,14 @@ function mergeSort(array, cmp) { return _ms(array); }; -// this function is taken from Acorn [1], written by Marijn Haverbeke -// [1] https://github.com/marijnh/acorn function makePredicate(words) { - if (!(words instanceof Array)) words = words.split(" "); - var f = "", cats = []; - out: for (var i = 0; i < words.length; ++i) { - for (var j = 0; j < cats.length; ++j) - if (cats[j][0].length == words[i].length) { - cats[j].push(words[i]); - continue out; - } - cats.push([words[i]]); - } - function quote(word) { - return JSON.stringify(word).replace(/[\u2028\u2029]/g, function(s) { - switch (s) { - case "\u2028": return "\\u2028"; - case "\u2029": return "\\u2029"; - } - return s; - }); - } - function compareTo(arr) { - if (arr.length == 1) return f += "return str === " + quote(arr[0]) + ";"; - f += "switch(str){"; - for (var i = 0; i < arr.length; ++i) f += "case " + quote(arr[i]) + ":"; - f += "return true}return false;"; - } - // When there are more than three length categories, an outer - // switch first dispatches on the lengths, to save on comparisons. - if (cats.length > 3) { - cats.sort(function(a, b) {return b.length - a.length;}); - f += "switch(str.length){"; - for (var i = 0; i < cats.length; ++i) { - var cat = cats[i]; - f += "case " + cat[0].length + ":"; - compareTo(cat); - } - f += "}"; - // Otherwise, simply generate a flat `switch` statement. - } else { - compareTo(words); - } - return new Function("str", f); -}; + if (!Array.isArray(words)) words = words.split(" "); + var map = Object.create(null); + words.forEach(function(word) { + map[word] = true; + }); + return map; +} function all(array, predicate) { for (var i = array.length; --i >= 0;) |