Last active
June 12, 2017 14:28
-
-
Save ryardley/dc394fa3a7aacc24a9aa1e5475e7b67d to your computer and use it in GitHub Desktop.
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
// ====================================== | |
// HIGHER ORDER CURRIED ARROW FUNCTIONS | |
// ====================================== | |
// Double arrows are great for creating functions | |
// that dont need all their arguments at once | |
// This is best for functions that need configuration | |
// before running on an active value. | |
// So here we have a function called | |
// setProp that is a curried arrow function: | |
const setProp = propName => value => ({ | |
[propName]: value, | |
}); | |
// It is the same as this: | |
function setProp(propName) { | |
return function (value) { | |
return { | |
[propName]: value, | |
}; | |
}; | |
} | |
// I know this can get confusing... | |
// The thing to notice, is how the inner function | |
// just uses all the given parameters from all the functions | |
// Without this function in function stuff you could say it | |
// is actually very similar to this: | |
function setProp(propName, value){ | |
return { | |
[propName]: value, | |
}; | |
} | |
// All the meat of the function actually does here is | |
// create an object and sets a property called by whatever | |
// is set in `propName` to the value `value`. | |
// We get some pretty awesome stuff from that function in function business. | |
// You see first Javascript closures mean that the inner function inherits all | |
// its variables from the outer function(s) | |
// What is important about that is that it allows us to configure the | |
// function at one point in the code and then give it the next argument | |
// at another later point. | |
// This is awesome when doing functional things like using array.map or | |
// array.reduce where you need a function that accepts only | |
// one argument in order to get the desired result | |
function getUsers() { | |
const usernames = ['fred', 'harry', 'george']; | |
return usernames.map(setProp('username')); | |
} | |
/* getUsers() returns: | |
[ | |
{ username: 'fred' }, | |
{ username: 'harry' }, | |
{ username: 'george' } | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment