Skip to content

Instantly share code, notes, and snippets.

@stefanfrede
Created June 7, 2016 05:40
Show Gist options
  • Save stefanfrede/cb7907db7801b3adc97c32a44bbeb57a to your computer and use it in GitHub Desktop.
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.
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