了解如何在香草JavaScript中实现lodash的_.flowRight

Ant*_*tiz 4 javascript recursion closures lodash

在学校里,我们的任务是构建lodash方法flowRight的实现!

在规格中提到:

接受任意数量的函数,并返回一个使用其参数的新函数,并从右到左(最后到第一个)调用提供的函数。每个函数(第一个函数除外)的参数由函数右侧的返回值确定。由flowRight返回的函数的调用求值为最左边的函数的返回值。

这是他们提供的示例:

e.g.

var sayHello = function (name) {
    return 'Hello, ' + name;
},

addExclamation = function (s) {
    return s + '!';
},

smallTalk = function (s) {
    return s + ' Nice weather we are having, eh?';
};

var greetEnthusiastically = flowRight(addExclamation, sayHello);

greetEnthusiastically('Antonio');
// --> returns 'Hello, Antonio!'
//(sayHello is called with 'Antonio', 
//  addExclamation is called with 'Hello, Antonio')
Run Code Online (Sandbox Code Playgroud)

我感觉像我了解一个静态示例(该示例演示)中发生的事情。

function (func1, func2) {
    return function(value) {
        return func1(func2(value));
    }
}
Run Code Online (Sandbox Code Playgroud)

猜猜我很难将自己的大脑环绕在循环中,我认为这是您所需要的。到目前为止,这是我的实现。

var flowRight = function (...args) {
    var Func;
    for(var i = args.length - 2; 0 > i; i--) {
        function Func(value) {
            return args[i](args[i + 1](value));
        }
    }
    return Func;
};
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

kem*_*toe 5

无需循环。如果允许,它将使用ES6。

此用途spreadrest以及reduce

const flowRight = (...functions) => functions.reduce((a, c) => (...args) => a(c(...args)));
Run Code Online (Sandbox Code Playgroud)

下面的例子

const flowRight = (...functions) => functions.reduce((a, c) => (...args) => a(c(...args)));
Run Code Online (Sandbox Code Playgroud)


sub*_*aze 5

要从右向左流动,您可以使用...spreadwith.reduceRight(x, y)

我已经对下面的代码进行了评论,以尝试解释这一切是如何协同工作的。

const sayHello = function (name) {
  return 'Hello, ' + name;
 };

const addExclamation = function (s) {
  return s + '!';
};

const smallTalk = function (s) {
  return s + ' Nice weather we are having, eh?';
}

// function that takes functions and then
// returns a function that takes  a value to apply to those functions in reverse
const flowRight = (...fns) => val => fns.reduceRight((val, fn) => {
  // return the function and pass in the seed value or the value of the pervious fn.
  // You can think of it like the following.
  // 1st pass: sayHello(value) -> "Hello, " + value;
  // 2nd pass: addExclamation("Hello,  $value") -> "Hello,  $value" + "!";
  // 3rd pass: smallTalk("Hello,  $value!") -> "Hello,  $value!" + ' Nice weather we are having, eh?'
  // ... and so on, the reducer will keep calling the next fn with the previously returned value
  return fn(val)
// seed the reducer with the value passed in
}, val);

var greetEnthusiastically = flowRight(smallTalk, addExclamation, sayHello);

console.log(greetEnthusiastically('Antonio'));
Run Code Online (Sandbox Code Playgroud)