javascriptfunction-composition

How can I use an array as a composition function argument?


I have trouble with building composition function, using an array as an argument. Got this error

TypeError: arr.map is not a function

const testArray = ["CusTom", "Web", "aNd", "MoBile", "PlaTfoRms"];

const compose =
  (...fncs) =>
  (val) =>
    fncs.reduceRight((acc, fnc) => fnc(acc), val);

const modifyArray = (ModifyCondition) => (data) => ModifyCondition(data);

let capitalizeAllFirst = modifyArray(
  compose(
    (arr) =>
      arr.map(
        (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
      ),
    (arr) => arr.join("-")
  )
);

let allToLower; // use compose + modifyArray here

console.log(capitalizeAllFirst(testArray));

I tried to use one argument in compose and it worked well

let capitalizeAllFirst = modifyArray(
  compose(
    (arr) =>
      arr.map(
        (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
      )
  )
);

Solution

  • Your code is perfect, except that you used reduceRight instead of reduce. This means that you'd joined the array into a string prior to then attempting to treat it as an array to capitalize it.

    const testArray = ["CusTom", "Web", "aNd", "MoBile", "PlaTfoRms"];
    
    const compose = (...fncs) =>
      val => fncs.reduce((acc, fnc) => fnc(acc), val);
    
    const modifyArray = modifyCondition => data => modifyCondition(data);
    
    let capitalizeAllFirst = modifyArray(compose(
      arr => arr.map(
        str => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
      ),
      arr => arr.join("-")
    ));
    
    console.log(capitalizeAllFirst(testArray));