aboutsummaryrefslogtreecommitdiff
path: root/src/utility.js
diff options
context:
space:
mode:
authorAlon Zakai <alonzakai@gmail.com>2011-08-26 14:29:52 -0700
committerAlon Zakai <alonzakai@gmail.com>2011-08-26 14:29:52 -0700
commit67e4662ac91d5b514a96957d00b0a8db69bfcf65 (patch)
tree4231a8f7a2faa07c0ef627a7e88e71b9e9335cca /src/utility.js
parent5b3b4c5ca4e10ce6ea22fb24ea429cb2c7dc213d (diff)
optimize generateStructTypes and flatten
Diffstat (limited to 'src/utility.js')
-rw-r--r--src/utility.js28
1 files changed, 22 insertions, 6 deletions
diff --git a/src/utility.js b/src/utility.js
index 7ab9e1ed..1b0a14f3 100644
--- a/src/utility.js
+++ b/src/utility.js
@@ -196,16 +196,32 @@ function isArray(x) {
}
}
+// Flattens something like [5, 6, 'hi', [1, 'bye'], 44] into
+// [5, 6, 'hi', 1, bye, 44].
function flatten(x) {
- if (typeof x !== 'object') return x;
- var ret = [];
- for (var i = 0; i < x.length; i++) {
- if (typeof x[i] === 'number') {
- ret.push(x[i]);
+ if (typeof x !== 'object') return [x];
+ // Avoid multiple concats by finding the size first. This is much faster
+ function getSize(y) {
+ if (typeof y !== 'object') {
+ return 1;
} else {
- ret = ret.concat(flatten(x[i]));
+ return sum(y.map(getSize));
+ }
+ }
+ var size = getSize(x);
+ var ret = new Array(size);
+ var index = 0;
+ function add(y) {
+ for (var i = 0; i < y.length; i++) {
+ if (typeof y[i] !== 'object') {
+ ret[index++] = y[i];
+ } else {
+ add(y[i]);
+ }
}
}
+ add(x);
+ assert(index == size);
return ret;
}