javascriptreplaceramda.js

Bracket syntax in Ramda replace function


I've used JavaScript for quite a long time, yet am struggling to understand how this example from the Ramda docs works:

const greet = R.replace('{name}', R.__, 'Hello, {name}!');
greet('Alice'); //=> 'Hello, Alice!'

How is the {name} variable/match recognized and then later interpolated into the Hello, {name} string? Is this a Ramda feature? A JavaScript trick? I've never seen this pattern before.

I checked the Ramda replace source code and couldn't find anything.


Solution

  • There's nothing special going on with {name} or replace. R.__ creates a partially applied function where the argument in that position is supplied later.

    It might help to see it written this way-

    const greet = R.replace('{name}', R.__, 'Hello, {name}!');
    
    const greet = function(replacement) {
      return R.replace('{name}', replacement, 'Hello, {name}!')
    }
    

    You can see it working here without the R.replace function -

    const stringReplace = R.curry((pattern, replacement, s) =>
      s.replace(pattern, replacement) // String.prototype.replace
    )
    
    const greet = stringReplace("***", R.__, "hello ***")
    console.log(greet("world")) // hello world
    console.log(greet("earth")) // hello earth
    

    The "magic" of R.__ is made possible because every function in the Ramda library is curried with its curry helper. A curried function waits for all of its arguments before it is finally applied and R.__ allows you to apply arguments out of position.