Create a function that accepts a single parameter
Quite often, we use the
map function to transform each item of an array into a new one. However, it's common to see an issue if we don't pass the parameter to the mapper function.
For example, the following code converts each item of array into a number:
['1', '2', '3', '4', '5'].map((v) => parseInt(v));
However, the result isn't correct if we shorten it as below:
['1', '2', '3', '4', '5'].map(parseInt);
The issue is caused by the fact that the mapper function accepts three parameters which are the array item, index, and the array.
.map(parseInt) means that we pass the item index to
parseInt as the second parameter. As a result, we will see
const unary = (fn) => (params) => fn(params);
unary function creates a wrapper of a function, and ignores all parameters except the first one. With that function in our hand, we can pass the mapper to the
map function like this:
['1', '2', '3', '4', '5'].map(unary(parseInt));