Skip to content

Instantly share code, notes, and snippets.

@carlsednaoui
Created July 9, 2013 16:48
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 carlsednaoui/5959036 to your computer and use it in GitHub Desktop.
Save carlsednaoui/5959036 to your computer and use it in GitHub Desktop.
Create Map and Reduce from scratch in JS.
Array.prototype.reduce = function(fn, acc) {
if (acc === undefined && this.length !== 0)
return this.slice(1).reduce(fn, this[0]);
if (this.length === 0) return acc;
return this.slice(1).reduce(fn, fn(acc, this[0]));
};
Array.prototype.map = function(fn) {
return this.reduce(function(acc, el) {
return acc.concat(fn(el));
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment