Skip to content

Instantly share code, notes, and snippets.

@debjitbis08
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debjitbis08/034b6de9b6839875f535 to your computer and use it in GitHub Desktop.
Save debjitbis08/034b6de9b6839875f535 to your computer and use it in GitHub Desktop.
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