aboutsummaryrefslogtreecommitdiff
path: root/lib/utils.js
diff options
context:
space:
mode:
authorMihai Bazon <mihai@bazon.net>2012-10-11 11:52:05 +0300
committerMihai Bazon <mihai@bazon.net>2012-10-11 11:52:05 +0300
commitf4584af42c8baa0a8f221adf1ff9a85765163e4b (patch)
tree94bc9505cebf8fcf4143715b733266976cb2069a /lib/utils.js
parent172aa7a93ccd39feceefa058ad008e19eec0a073 (diff)
downloadtracifyjs-f4584af42c8baa0a8f221adf1ff9a85765163e4b.tar.gz
tracifyjs-f4584af42c8baa0a8f221adf1ff9a85765163e4b.zip
using makeComparator from acorn to generate functions that tests whether a
string is keyword, reserved etc. speeds up the parser a bit, though not spectacular.. still far from acorn.
Diffstat (limited to 'lib/utils.js')
-rw-r--r--lib/utils.js37
1 files changed, 37 insertions, 0 deletions
diff --git a/lib/utils.js b/lib/utils.js
index 33dc8ff2..d18e62ee 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -214,3 +214,40 @@ function set_intersection(a, b) {
return b.indexOf(el) >= 0;
});
};
+
+// 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 compareTo(arr) {
+ if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
+ f += "switch(str){";
+ for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(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);
+};