Skip to content

Instantly share code, notes, and snippets.

@tyb
Created December 6, 2020 23:59
Show Gist options
  • Save tyb/7038410a712362c741413b62807e43e4 to your computer and use it in GitHub Desktop.
Save tyb/7038410a712362c741413b62807e43e4 to your computer and use it in GitHub Desktop.
Created with Copy to Gist
We will rewrite the JavaScript array map function in a functional manner.
function map(fn) {
return function(arr) {
return Array.prototype.map.call(arr, fn)
}
}
map(function(x) {return x * x}) ([1, 2, 3]) //==>> [ 1, 4, 9 ]
Notice that the arguments are flipped. The function comes first then the array. Also we used Array.prototype.map.call instead of just calling arr.map. This is so that we can use our map function with array like objects, arguments and DOMNodeList.
Say you wanted to get all the emails from a list like this in an array.
var people = [ {name:”John”, email:”john@example.com”},
{name:”Bill”, email:”bill@example.com”} ]
map(get(‘email’)) (people)
//===>> [ ‘john@example.com’, ‘bill@example.com’ ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment