redux compose.js

//  compose.js 源码
function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }
  return funcs.reduce((a, b) => (...args) =>return a(b(...args)))
}

简单实现 reduce

function fun0(v) {
  return v+'fun0'
}
function fun1(v) {
  return v+'fun1'
}
function fun2(v) {
  return v+'fun2'
}

function fun3(v) {
  return v+'fun3'
}

// 传入一个数组(此处[]:function),
// 和一个回调函数,迭代执行回调,入参为(前一次回调返回的值,当前要迭代的元素) 
function rreduce(arr=[],callback=()=>{}) {
  if(!arr.length) throw new Error('arga[0] should be array;');
  const len = arr.length;
  let k = 0;// 索引
  let value = arr[0];
  while (k右
const res = rreduce([fun0,fun1,fun2,fun3],function (pre,current) {
  return (...arguments)=>{
  // arguments为初始值1
    return current(pre(...arguments))
  }
})(1);

console.log(res); // 1fun0fun1fun2fun3

你可能感兴趣的:(redux compose.js)