Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 新旧替换五:函数嵌套 #59

Open
XXHolic opened this issue Oct 13, 2019 · 0 comments
Open

JavaScript 新旧替换五:函数嵌套 #59

XXHolic opened this issue Oct 13, 2019 · 0 comments

Comments

@XXHolic
Copy link
Owner

XXHolic commented Oct 13, 2019

目录

引子

看了 ReduxapplyMiddleware 方法的实现,里面函数嵌套的写法都用了新语法,就想关注一下函数嵌套一类新旧的不同。

上一篇 JavaScript 新旧替换四:继承

ES5 方式

普通嵌套

  function find(value) {
    return {
      in: function(arr) {
        return {
          combine: function(obj) {
            var result = arr.indexOf(value);
            obj.index = result;
            return obj;
          }
        };
      }
    };
  }

  var data = find(6).in([1,2,3,4,5,6]).combine({});
  console.info(data); // {index: 5}

管道机制

管道机制(pipeline)是指前一个函数的输出是后一个函数的输入。

  const plus = a => a + 1;
  const minus = a => a - 2;
  const multi = a => a * 3;
  const div = a => a / 4;

  function pipeline() {
    for (var len = arguments.length, funcs = [], key = 0; key < len; key++) {
      funcs[key] = arguments[key];
    }

    return function(val) {
      var result = funcs.reduce(function(a, b) {
        return b(a);
      }, val);
      return result;
    };
  }

  var cal = pipeline(plus,minus,multi,div);
  var result = cal(5);
  console.info(result); // 3

ES2015+ 方式

普通嵌套

  const find = (value) => (
    {
      in: (arr) => (
        {
          combine: (obj) => {
            const result = arr.indexOf(value);
            obj.index = result;
            return obj;
          }
        }
      )
    }
  );

  const data = find2(6).in([1,2,3,4,5,6]).combine({});
  console.info(data); // {index: 5}

管道机制

  const plus = a => a + 1;
  const minus = a => a - 2;
  const multi = a => a * 3;
  const div = a => a / 4;

  const pipeline = (...funcs) => val => funcs.reduce(function(a,b) {
    return b(a);
  }, val);

  const cal = pipeline(plus,minus,multi,div);
  const result = cal(5);
  console.info(result); // 3

参考资料

🗑️

以下是一些无关紧要的内容。

虽然《哪吒之魔童降世》还在电影院上线,但各大视频平台已经拿到版权,可以放映了,看了下播放量,还是有不少。

这部动画电影感觉是一个全新的故事,也是一个好听的故事。

帅气逼人的太乙真人

52-tyzr

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant