Skip to content

Instantly share code, notes, and snippets.

@Genovo
Last active February 25, 2018 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Genovo/d765b1f32f9da513c8313f6039b300a7 to your computer and use it in GitHub Desktop.
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.
const unary = (fn) =>
fn.length === 1
? fn
: function (something) {
return fn.call(this, something)
}
['1', '2', '3'].map(unary(parseInt))
//=> [1, 2, 3]
@Genovo
Copy link
Author

Genovo commented Feb 25, 2018

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:

['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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment