Created
June 7, 2016 05:40
-
-
Save stefanfrede/cb7907db7801b3adc97c32a44bbeb57a to your computer and use it in GitHub Desktop.
Unary takes any function and turns it into a function taking exactly one argument.
This file contains hidden or 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
const unary = (fn) => | |
fn.length === 1 | |
? fn | |
: function (something) { | |
return fn.call(this, something); | |
}; | |
/** | |
* Example use case | |
* | |
* JavaScript’s map calls each function with | |
* three arguments: The element, the index of | |
* the element in the array, and the array | |
* itself. | |
*/ | |
// If you pass in a function taking only one argument, | |
// it simply ignores the additional arguments | |
['1', '2', '3'].map(parseFloat); | |
//=> [1, 2, 3] | |
// But some functions have optional second or even third | |
// arguments. | |
['1', '2', '3'].map(parseInt); | |
//=> [1, NaN, NaN] | |
// This doesn’t work because parseInt is defined as | |
// parseInt(string[, radix]). It takes an optional radix | |
// argument. And when you call parseInt with map, the index | |
// is interpreted as a radix. | |
// To fix it use the unary decorator. | |
['1', '2', '3'].map(unary(parseInt)); | |
//=> [1, 2, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment