Created
December 6, 2020 23:59
-
-
Save tyb/7038410a712362c741413b62807e43e4 to your computer and use it in GitHub Desktop.
Created with Copy to Gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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