Skip to content

Instantly share code, notes, and snippets.

@AutoSponge
Last active December 16, 2015 02:49
Show Gist options
  • Save AutoSponge/5365685 to your computer and use it in GitHub Desktop.
Save AutoSponge/5365685 to your computer and use it in GitHub Desktop.
function shift(arr, i) {
var cut = arr.length - i;
return arr.slice(cut).concat(arr.slice(0, cut));
}
var arr = [1,2,3,4,5];
shift(arr, 1); //[5, 1, 2, 3, 4]
shift(arr, 3); //[3, 4, 5, 1, 2]
function cartWith(fn, a, b) {
var copyA = a.slice(0);
var copyB = b.slice(0);
var result = [];
while (copyA.length) {
result.push.apply(result, (copyB.map(fn.bind(this, copyA.shift()))));
}
return result;
}
function sum(a, b) {
return a + b;
}
function makeVariadic(fn) {
return function () {
var args = Array.prototype.slice.call(arguments, 0);
var a, result;
var b = args.pop();
while (args.length) {
a = args.pop();
b = fn(a, b);
}
return b;
};
}
makeVariadic(cartWith.bind(null, sum))(["a", "b"], [1,2,3], ["x", "y"]);
function cartWith(fn, a, b) {
var copyA = a.slice(0);
var copyB = b.slice(0);
var result = [];
while (copyA.length) {
result.push.apply(result, (copyB.map(fn.bind(this, copyA.shift()))));
}
return result;
}
function sum(a, b) {
return a + b;
}
cartWith(sum, ["a", "b"], [1,2,3]);
cartWith(sum, ["a", "b"], cartWith(sum, [1,2,3], ["x", "y"]));
function tuple(a, b) {
return [a].concat(b);
}
cartWith(tuple, ["a", "b"], cartWith(tuple, [1,2,3], ["x", "y"]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment