I'm attempting to write a compose function which can accept an arbitrary number of functions, store them in a closure, and apply each of those functions to an initial value. The actual application of the function composition executes in a tail call recursion _lCompose(). The issue I'm running into is the base case will console.log('acc', acc) the correct value but 'return acc' returns undefined

function addOne (a ) {
    console.log('addone', a, a + 1)
    return a + 1
}
function double (a) {
    console.log('double', a, a * 2)
    return a * 2;
}
function square (a) {
    console.log('square', a, a * a)
    return a * a;
}

const lCompose = (...args) => {

    function _lCompose ( initialValue, acc, ...args ) {
        //base case when no args remain, return acc
        if ( !args.length ) {
            console.log('acc', acc)
            return acc;
        } else {
            // recurse, shift ...args and call head(acc)
            const [head, ...tail] = args;
            console.log('head', head)
            const _acc = head(acc);
            _lCompose (initialValue, _acc, ...tail )
        }
    }
    // use _v twice to set as initial value and initial accumulator
    return (initV, initAcc) =>  _lCompose(initV, initAcc, ...args)
}

const trans = lCompose(addOne, double, square);
trans(5, 5) // should return 144
1

There are 1 answers

1
Oriol On BEST ANSWER

Because you forgot to return the result of the recursive call.

return _lCompose (initialValue, _acc, ...tail )

const addOne = a => a + 1;
const double = a => a * 2;
const square = a => a * a;
const lCompose = (...args) => {
  function _lCompose ( initialValue, acc, ...args ) {
    if ( !args.length ) {
      return acc;
    } else {
      const [head, ...tail] = args;
      const _acc = head(acc);
      return _lCompose (initialValue, _acc, ...tail )
    }
  }
  return (initV, initAcc) =>  _lCompose(initV, initAcc, ...args)
}
const trans = lCompose(addOne, double, square);
console.log(trans(5, 5)); // 144