Skip to content

Instantly share code, notes, and snippets.

@kiinlam
Last active June 10, 2019 11:05
Show Gist options
  • Save kiinlam/4bb947e0d8986b954273feb04796d6c6 to your computer and use it in GitHub Desktop.
Save kiinlam/4bb947e0d8986b954273feb04796d6c6 to your computer and use it in GitHub Desktop.
es6实现pipeline效果
function pipe(data, ...args) {
return args.reduce((r, f) => f(r), data);
}
//test
function f1(a) {
a.pop();
return a;
}
function f2(a) {
return a.reverse()
}
//[1,2,3]经过两个function的处理后,输出结果
pipe([1,2,3], f1, f2) // => [2,1]
@kiinlam
Copy link
Author

kiinlam commented Jun 10, 2019

使用Proxy实现:

var pipe = (function () {
  return function (value) {
    var funcStack = [];
    var oproxy = new Proxy({} , {
      get : function (pipeObject, fnName) {
        if (fnName === 'get') {
          return funcStack.reduce(function (val, fn) {
            return fn(val);
          },value);
        }
        funcStack.push(window[fnName]);
        return oproxy;
      }
    });

    return oproxy;
  }
}());

var double = n => n * 2;
var pow    = n => n * n;
var reverseInt = n => n.toString().split("").reverse().join("") | 0;

pipe(3).double.pow.reverseInt.get; // 63

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment