Here's where it starts: This below snippet doesn't work as expected:
['1', '2', '3'].map(parseInt) // [1, NaN, NaN] <- bad output
A simple change remedies it:
['1', '2', '3'].map(a => parseInt(a)) // [ 1, 2, 3 ] <- good output
But this book I'm reading has a different remedy:
Create a unary
function, which takes in a function (parseInt
in our case) and if the function has n
arguments, it returns a new function that has only a single argument. Here's how the book does it:
const unary = (f) => {
return f.length === 1 ? f : (args) => f(args)
}
['1', '2', '3'].map(unary(parseInt)) // [ 1, 2, 3 ] <- good output again!
My question is:
- How is this
unary
function is working? - Any practical scenario where this function (or at least this idea in general) will find a good use?
Any help would be much appreciated :)
Note to the future reader: Checkout currying