Weird function syntax

With this closure, you could get a function with a constant value for later adding.

  1. How could this be used in real life?

You could take the returned function for a mapping of an array.

  1. What's the advantage of not using a function with 2 parameters and using this instead (for a one-line function)?

It's a cleaner and functional approach.

const
    x = a => b => a + b,
    add5 = x(5);

console.log([1, 2, 3].map(add5));


Let's give that function a better name:

const add = (a) => (b) => a + b

Then later you can write

[1, 2, 3, 4] .map (add (5)) //=> [6, 7, 8, 9]

which is nicer to read than

[1, 2, 3, 4] .map ((n) => 5 + n) //=> [6, 7, 8, 9]

This is handy in a chain of .then() calls on Promises:

  return fetchList (param)
    .then (map (add (5)))
    .then (filter (lessThan (8)))
    .then (average)

(This of course requires curried functions add, lessThan, map, and filter, and some simple average function.)

Compare this to

  return fetchList (param)
    .then (xs => xs.map (x => add (5, x)))
    .then (xs => xs.filter (x => lessThan (8, x)))
    .then (average)

Note that the reason that average works the same in both versions of this is that it takes a single parameter. One major point of currying is to turn a function into one that takes a single parameter. It makes a certain style of coding much easier to perform.


Nina gave an excellent answer. I will provide another, a little more advanced example where such closures help a lot with the clarity of the code. Let's combine functions together into a prefix-checker as below and then re-use it as many times as we want:

//given a word, check if a string s starts with this word
const literal = word => s => s && s.startsWith(word);

//allow to combine 2 literals with OR    
const either = (p1, p2) => s => p1(s) || p2(s);

//allow to combine N literals
const any = (...parsers) => parsers.reduce(either);

//create a parser
const check = any(literal('cat'),literal('dog'),literal('cow'));

console.log('cat: ' + check('cat'));
console.log('dog: ' + check('dog is smart'));
console.log('cow: ' + check('cow 123'));
console.log('banana: ' + check('banana'));

In reality, it is a simplified parser-combinator (nope, not yet monadic). Extending this approach, you can create parsers for your own programming language, and it would be maintainable and fast.

Tags:

Javascript