Search code examples
javascriptfunctional-programmingramda.js

Avoid custom lamda function for Ramdajs map


Array of functions, which is mapped over, is being invoked using fat arrow syntax.

import R from 'ramda';

const arrFn = [R.multiply(2), R.identity, R.add(3)];

const testData = 2;

// is there way to avoid custom lamda fn
const result = R.map((x) => x(testData))(arrFn);

console.log('result', result);

Are there any ramda.js helper fns which can avoid the arrow syntax?

Stackblitz


Solution

  • I would use applySpec for this. It's not well-documented to handle arrays; its only example is an object. But it works fine for arrays of functions, just as it does for something like applySpec ({foo: multiply (2), bar: {baz: identity, qux: add (3)}}) (2) yielding {foo: 4, bar: {baz: 2, qux: 5}}. Here it would just be:

    const {applySpec, multiply, identity, add} = R
    
    const arrFn = [multiply (2), identity, add (3)]
    const testData = 2
    
    console .log (applySpec (arrFn) (testData))
    <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>

    You could also use juxt (short for "juxtapose" -- don't ask!) but that is not one of Ramda's better-designed functions.

    const {juxt, multiply, identity, add} = R
    
    const arrFn = [multiply (2), identity, add (3)]
    const testData = 2
    
    console .log (juxt (arrFn) (testData))
    <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>