Skip to content

Instantly share code, notes, and snippets.

@noonat noonat/concat-reduce-1.js
Last active Dec 30, 2015

Embed
What would you like to do?
// really slow: ~50s
try {
return ret.concat.apply([], ret);
} catch (e) {
if (e instanceof RangeError && ret.reduce) {
return ret.reduce(function(a, b) {
return a.concat(b);
}, [])
} else {
throw e;
}
}
// also slow: ~45s
try {
return ret.concat.apply([], ret);
} catch (e) {
if (e instanceof RangeError) {
var flat = [];
for (var i = 0, il = ret.length; i < il; ++i) {
flat = flat.concat(ret[i]);
}
return flat;
} else {
throw e;
}
}
// much better! ~2ms w/ native isArray, ~15ms w/out
try {
return ret.concat.apply([], ret);
} catch (e) {
if (e instanceof RangeError) {
var flat = [], isArray = Array.isArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
for (var i = 0, il = ret.length; i < il; ++i) {
var item = ret[i];
if (isArray(item)) {
flat = flat.concat(item);
} else {
flat.push(item);
}
}
return flat;
} else {
throw e;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.