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));?
2
  • 1
    Replace the arrow functions with their old-school function() versions. This might be easier to understand. Commented Jun 22, 2020 at 12:36
  • 2
    Very relevant: What do multiple arrow functions mean in javascript? Commented Jun 22, 2020 at 12:36

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

.reduceRight() has only one required parameter -> reducer. The initialValue is optional.
@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?
@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
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'));

1 Comment

could you take a look please, thanks: stackoverflow.com/questions/63345237/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.