了解函数式编程中的 compose 吗?动手实现一下?

const greeting = (name) => `hello ${name}`;const toUpper = (str) => str.toUpperCase();const fn = compose(toUpper, greeting);console.log(fn('Lucy'));// HELLO LUCY
方式一:
function compose(...fns) {let isFirst = true;return (...args) => {return fns.reduceRight((result, fn) => {if (!isFirst) return fn(result);isFirst = false;return fn(...result);}, args);};}
方式二:
function compose(...fns) {let len = fns.length,count = len - 1,result = null;// 首先compse 返回的是一个函数return function fn(...args) {// 函数体里就是不断执行args函数,将上一个函数的执行结果作为下一个执行函数的输入参数,需要一个count来记录args函数列表的执行情况result = fns[count].apply(this, args);// 递归退出条件if (count <= 0) {count = len - 1;return result;} else {count--;return fn.call(null, result);}};};
方式三:
参考:
https://github.com/lgwebdream/FE-Interview/issues/1039
