Reputation: 234
I have a trouble to understand the return value from line #14. My question is about: fn(acc), x
in one line. How is it possible to write it in a block instead? Like: {return fn(acc), x}
?? Of course it wouldn't work. Does any one can write it down as a block code instead of a one-line code?
1 const scream = str => str.toUpperCase()
2 const exclaim = str => `${str}!`
3 const repeat = str => `${str} ${str}`
4
5 const string = 'Hello world'
6
7 // Nested
8 // const result1= repeat(exclaim(scream(string)))
9 // console.log(result1)
10 // HELLO WORLD! HELLO WORLD!
11
12 // Instead of nesting, compose your functions into a new function
13 const compose = (...fns) => x =>
14 fns.reduceRight((acc, fn) => fn(acc), x)
15
16 const enhance = compose(repeat, exclaim, scream)
17 const result2 = enhance(string)
18 console.log(result2)
19 // HELLO WORLD! HELLO WORLD!
Thanks!
Upvotes: 1
Views: 58
Reputation: 123540
The thing to note is mostly that reduceRight
is a reverse for loop. Here is the same function with loops and regular function expressions:
const scream = str => str.toUpperCase()
const exclaim = str => `${str}!`
const repeat = str => `${str} ${str}`
const string = 'Hello world'
// (...fns) =>
function compose() {
var fns = arguments;
// x =>
return function(x) {
var acc = x;
// fns.reduceRight((acc, fn) =>
for(var i = fns.length-1; i>=0; i--) {
var fn = fns[i];
// fn(acc)
acc = fn(acc);
}
return acc;
}
}
const enhance = compose(repeat, exclaim, scream)
const result2 = enhance(string)
console.log(result2)
Upvotes: 1