Last active
February 25, 2018 15:56
-
-
Save Genovo/d765b1f32f9da513c8313f6039b300a7 to your computer and use it in GitHub Desktop.
“Unary” is a function decorator that modifies the number of arguments a function takes: Unary takes any function and turns it into a function taking exactly one argument.
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
const unary = (fn) => | |
fn.length === 1 | |
? fn | |
: function (something) { | |
return fn.call(this, something) | |
} | |
['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
The most common use case is to fix a problem. For eaxmple, JavaScript has a .map method for arrays, and many
libraries offer a map function with the same semantics. But JavaScript’s map actually calls each function with three arguments: The element,
the index of the element in the array, and the array itself. f you pass in a function taking only one argument, it simply ignores the additional arguments. But Some functions have optional second or even third arguments. For example:
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.