当前位置: 代码迷 >> 综合 >> redux componse 函数中的反向职责链模式的演变
  详细解决方案

redux componse 函数中的反向职责链模式的演变

热度:85   发布时间:2023-11-21 05:22:09.0

最初的实现方式   核心是 reduceRight 方法 把前一个执行结果 作为下一个的参数执行  

function add1(str){return str+1;
}
function add2(str){return str+2;
}const componse = (...fns)=>(...args){let last = fns.pop();return fns.reduceRight((prev,current)=>{return current(prev);},last(...args));
}let add = componse(add2,add1);let res = add("test");console.log(res);

最终 一行代码搞定版  

function add1(str){return str+1;
}
function add2(str){return str+2;
}function add3(str){return str+3;
}
//此处componse 函数的逻辑 为  返回值: reduce 的返回值为最终的结果 此处也就是(...args)函数  
//所以下面的add的值就是该函数  // 第一次执行的时候a的值为add3  b的值为add2  
//第二次执行的时候 a的值就是add3(add2)的结果 b的值就是add1
//所以这个地方就有个递归的关系  也就是实际的执行结果是从右往做的function componse(...fns){return fns.reduce((a,b)=>(...args)=>a(b(...args)));
}let add = componse(add3,add2,add1);let res = add("test");console.log(res);