Skip to content

Instantly share code, notes, and snippets.

@allouis
Last active August 26, 2015 15:23
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 allouis/96e2b9dbadcaa0e9004e to your computer and use it in GitHub Desktop.
Save allouis/96e2b9dbadcaa0e9004e to your computer and use it in GitHub Desktop.
reduce implemented recursively, no state
function compose(f, g) {
return function(x) {
return f(g(x));
}
}
function cons(arr) {
return function (val) {
return arr.concat(val);
}
}
function map(fn, arr) {
return reduce(arr, compose(cons([]), fn));
}
function first(arr) {
return arr[0];
}
function rest(arr) {
return Array.prototype.slice.call(arr, 1);
}
function reduce(value, fn, arr) {
return arr.length ? reduce(fn(value, first(arr), fn, rest(arr))) : value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment