1

I try to get some details from the code below:

const upperCase = str => str.toUpperCase();
const exclaim = str => `${str}!`;
const repeat = str => `${str} `.repeat(3);

const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);

const withСompose = compose(
  repeat,
  exclaim,
  upperCase
);

console.log(withСompose("hello")); 

Questions:

  1. How x from => x =>, go instead x from fn(acc), x);?
  2. Why const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x); does not work in this way const compose = (...fns) => fns.reduceRight((acc, fn) => fn(acc));?
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Asking
  • 3,487
  • 11
  • 51
  • 106
  • 1
    Replace the arrow functions with their _old-school_ `function()` versions. This might be easier to understand. – Andreas Jun 22 '20 at 12:36
  • 2
    Very relevant: [What do multiple arrow functions mean in javascript?](https://stackoverflow.com/q/32782922) – VLAZ Jun 22 '20 at 12:36

2 Answers2

2

1.2. because reduce right takes two arguments reduceRight(reducer, initialValue) the initial value in your case is the x itself

const upperCase = str => str.toUpperCase();
const exclaim = str => `${str}!`;
const repeat = str => `${str} `.repeat(3);
const reducer = (acc, fn) => fn(acc);
const compose = (...fns) => x => fns.reduceRight(reducer, x);

const withСompose = compose(
  repeat,
  exclaim,
  upperCase
);

console.log(withСompose("hello")); 

hope now it's clear

Olian04
  • 6,480
  • 2
  • 27
  • 54
  • [`.reduceRight()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) has only one required parameter -> `reducer`. The `initialValue` is optional. – Andreas Jun 22 '20 at 12:42
  • @Shandor Kostur, do i understand right, that writing this: `withСompose("hello")`, i create a curried function and `hello` in this case will go instead of `x` as initialValue? – Asking Jun 22 '20 at 12:50
  • @AskMen to be more concrete you've created partial application not curried function but yes you're right in this case hello is the initialValue of reduce right – Shandor Kostur Jun 22 '20 at 12:53
1

May help to figure out, result of compose:

const withСompose = function fnUpperCase(str1) {
    const resultStrFn1 = str1.toUpperCase();

    return (function fnExclaim(str2) {
        const resultStrFn2 = `${str2}!`;

        return (function fnRepeat(str3) {
            return `${str3} `.repeat(3);
        })(resultStrFn2);
    })(resultStrFn1);
};

console.log(withСompose('hello'));
Nikita Madeev
  • 4,284
  • 9
  • 20
  • could you take a look please, thanks: https://stackoverflow.com/questions/63345237/save-data-in-a-special-order-when-click-on-button – Asking Aug 10 '20 at 17:41