从lambda表达式返回值

时间:2018-06-18 18:42:49

标签: ecmascript-6

我很难理解第14行的返回值。我的问题是:fn(acc), x在一行中。怎么可能把它写在一个块中呢?喜欢:{return fn(acc), x} ??当然它不会起作用。有没有人可以把它写成块代码而不是单行代码?

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!

谢谢!

1 个答案:

答案 0 :(得分:1)

需要注意的是,reduceRight主要是反向循环。这是与循环和常规函数表达式相同的函数:

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)