Last active
August 29, 2015 14:08
-
-
Save briancavalier/8f953fd4c06a97645f06 to your computer and use it in GitHub Desktop.
Improve reduce perf, non-sparse arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dropping sparse array support makes this code much simpler | |
function reduce(promises, f) { | |
var hasArg = arguments.length > 2; | |
if((promises.length>>>0) === 0) { | |
return hasArg ? when.promise(arguments[2]) : when.reject(new TypeError('Cannot reduce empty array with no initial value')); | |
} | |
return hasArg ? runReduce(0, promises, f, arguments[2]) | |
: runReduce(1, promises, f, promises[0]); | |
} | |
function runReduce(i, promises, f, z) { | |
if (i === promises.length) { | |
return z; | |
} | |
return when.resolve(promises[i]).fold(function(z, x) { | |
return runReduce(i + 1, promises, f, f(z, x)); | |
}, z); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// With sparse array support | |
// See https://github.com/cujojs/when/pull/391 | |
function reduce(a, f) { | |
var hasArg = arguments.length > 2; | |
if((a.length>>>0) === 0) { | |
return hasArg ? toPromise(arguments[2]) : reject(new TypeError('Cannot reduce empty array with no initial value')); | |
} | |
var s = findFirst(a); | |
return hasArg ? runReduce(s, a, f, arguments[2]) | |
: runReduce(s + 1, a, f, a[s]); | |
} | |
function runReduce(i, a, f, z) { | |
if (i === a.length) { | |
return z; | |
} | |
var x = a[i]; | |
if(x === void 0 && !(i in a)) { | |
return runReduce(i + 1, a, f, z); | |
} | |
return toPromise(a[i]).fold(function (z, x) { | |
return runReduce(i + 1, a, f, f(z, x, i)); | |
}, z); | |
} | |
function findFirst(a) { | |
for(var i=0; i<a.length; ++i) { | |
if(i in a) { break; } | |
} | |
return i; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment