Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Double every other
var zipWith = function (fn, a, b) {
var l = Math.min(a.length, b.length),
r = [];
for(var i = 0; i < l; i += 1) {
r.push(fn(a[i], b[i]));
}
return r;
};
var mul = function (a, b) { return a * b; }
var cycle = function (a, n) {
var output = [];
for (var i = 0; i < n; i++) {
output.push(a[i % a.length]);
}
return output;
};
// doubleEveryOther
var list = [1,2,3,4,5];
zipWith(mul, cycle([1, 2], list.length), list);
/*
1,4,3,8,5
*/
var zipWith = function (fn, a, b) {
var l = Math.min(a.length, b.length),
r = [];
for(var i = 0; i < l; i += 1) {
r.push(fn(a[i], b[i]));
}
return r;
};
var apply = function (fn, v) {
return fn(v);
};
var id = function (v) { return v; }
var dbl = function (n) { return 2 * n; }
var cycle = function (a, n) {
var output = [];
for (var i = 0; i < n; i++) {
output.push(a[i % a.length]);
}
return output;
};
// doubleEveryOther
zipWith(apply, cycle([id, dbl], 10), [1,2,3,4,5]);
/*
1,4,3,8,5
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment