Skip to content

Instantly share code, notes, and snippets.

@hunan-rostomyan
Created March 22, 2016 17:00
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 hunan-rostomyan/68cbc5e9854d6a2559a1 to your computer and use it in GitHub Desktop.
Save hunan-rostomyan/68cbc5e9854d6a2559a1 to your computer and use it in GitHub Desktop.
Using reduce to define map [JS, Python]
// In a language with arrays, `reduce` can be used
// to accumulate arrays and thus can be used to
// define array-producing operators like `map`.
Array.prototype.map = function(fn) {
return this.reduce(function(sum, cur) {
return sum.concat(fn(cur));
}, []);
};
# In a language with lists, `reduce` can be used
# to accumulate lists and thus can be used to
# define list-producing operators like `map`.
def map(fn, lst):
return reduce(lambda sum, cur: sum + [fn(cur)], lst, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment