Skip to content

Instantly share code, notes, and snippets.

@webbower
Created August 19, 2014 23:31
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 webbower/ad63384c2e53db813b9e to your computer and use it in GitHub Desktop.
Save webbower/ad63384c2e53db813b9e to your computer and use it in GitHub Desktop.
Recursive implementations of map, filter, reduce
// Requires utils.list.js for first() and rest()
function map(callback, list) {
if (!list.length) return [];
else return [callback(first(list))].concat(map(callback, rest(list)));
}
function filter(predicate, list) {
if (!list.length) return [];
else return (predicate(first(list)) ? [first(list)] : []).concat(filter(predicate, rest(list)));
}
function reduce(callback, value, list) {
if (!list.length) return value;
else return reduce(callback, callback(value, first(list)), rest(list));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment