Skip to content

Instantly share code, notes, and snippets.

@TurplePurtle
Created January 5, 2016 23:08
Show Gist options
  • Save TurplePurtle/a0a9448d41ea5a6b6998 to your computer and use it in GitHub Desktop.
Save TurplePurtle/a0a9448d41ea5a6b6998 to your computer and use it in GitHub Desktop.
zipWith implementation
/*
* zipWith(...arrays, iteratee, [thisArg]) => array
*
* iteratee receives an element from each array as an argument
*/
function zipWith() {
// Argument count
var argc = arguments.length;
// Find iteratee, thisArg, and array count
var fn, thisArg, arrayCount;
if (typeof arguments[argc - 1] === "function") {
fn = arguments[argc - 1];
thisArg = null;
arrayCount = argc - 1;
} else if (typeof arguments[argc - 2] === "function") {
fn = arguments[argc - 2];
thisArg = arguments[argc - 1];
arrayCount = argc - 2;
} else {
throw new Error("Iteratee not supplied or extra arguments given after thisArg");
}
// Exit early if no arrays given
if (arrayCount === 0) return [];
// Find length of smallest array
var accLen = arguments[0].length;
for (var i = 1; i < arrayCount; i++) {
accLen = Math.min(accLen, arguments[i].length);
}
// Exit early if there is an empty array
if (accLen === 0) return [];
// Create accumulator of desired size
var acc = new Array(accLen);
// Populate accumulator
for (var j = 0; j < accLen; j++) {
var values = new Array(arrayCount);
for (var k = 0; k < arrayCount; k++) {
values[k] = arguments[k][j];
}
acc[j] = fn.apply(thisArg, values);
}
// Return accumulator
return acc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment