您当前的位置: 首页 > 

暂无认证

  • 4浏览

    0关注

    92582博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

使用函数实现函数调用扁平化 - compos

发布时间:2021-03-07 21:48:35 ,浏览量:4

目录
    • 1、功能函数
    • 2、第一种 compose 函数
    • 3、第二种 compose 函数
    • 4、调用
1、功能函数
let fn1 = function (x) { return x + 10; }; let fn2 = function (x) { return x * 10; }; let fn3 = function (x) { return x / 10; }; 
2、第一种 compose 函数
function compose(...funcs) { if (funcs.length === 0) { return arg => arg; } if (funcs.length === 1){ return funcs[0]; } return funcs.reduce((a, b) => (...args) => a(b(...args))); }; 
3、第二种 compose 函数
function compose(...funcs) { // funcs:传递的函数集合 return function proxy(...args) { // args:第一次调用函数传递的参数集合 let len = funcs.length; if(len === 0) { // 一个函数都不需要执行,直接返回 args return args; }; if(len === 1) { // 只需要执行一个函数,直接返回 args return funcs[0](...args); }; return funcs.reduce((x, y) => { return typeof x === "function" ? y(x(...args)) : y(x); }); }; }; 
4、调用
// 第三种调用方式(需要配合 compose 函数调用) compose()(5); compose(fn1)(5); compose(fn1, fn2)(5); compose(fn1, fn2, fn1, fn3)(5); // 第二种调用方式 let x = fn1(5); x = fn2(x); x = fn1(x); x = fn3(x); console.log(x); // 第一种调用方式 console.log(fn3(fn1(fn2(fn1(5))))); // => ((5+10)*10+10)/10 =>16 
关注
打赏
1653961664
查看更多评论
立即登录/注册

微信扫码登录

0.5101s