developer-plus / interview

https://interview.developer-plus.org
MIT License
9 stars 1 forks source link

手写组合函数 #22

Open Hongbusi opened 2 years ago

Hongbusi commented 2 years ago
function compose(...fns) {
  const length = fns.length
  for (let i = 0; i < length; i++) {
    if (typeof fns[i] !== 'function') {
      throw new TypeError('Expected arguments are functions')
    }
  }

  return function (...args) {
    let index = 0
    let result = length ? fns[index].apply(this, args) : args
    while (++index < length) {
      result = fns[index].call(this, result)
    }
    return result
  }
}

// test
function double(num) {
  return num * 2
}

function square(num) {
  return num ** 2
}

const newFn = compose(double, square)

console.log(newFn(10))
ChenHaoJie9527 commented 2 years ago

组合函数-简单版

// 简单实现组合函数
const compose =
  (...args: any[]) =>
  values => {
    return args.reverse().reduce((prev, curr) => curr(prev), values);
  };
const reverse = (arr: any[]) => arr.reverse();
const first = (arr: any[]) => arr[0];
const toUpper = (value: string) => value.toUpperCase();
const flowRight = compose(toUpper, first, reverse);
console.log('flowRight', flowRight(['a', 'b', 'flow']));
luckept commented 2 years ago

不知道理解得对不对

function compose(...fns) {
  let res
  return function(...args) {
    fns.forEach((fn) => {
      if (!res) {
        res = fn(...args)
      } else {
        res = fn(res)
      }
    })
    return res
  }
}
myltx commented 2 years ago

这样的也可以达到效果

/**
 * composeRight (参数从右往左)
 * compose (参数从左往右)
 */
export function composeRight(...fns) {
  return function (x) {
    return fns.reduceRight((v, f) => f(v), x);
  };
}
export function compose(...fns) {
  return function (x) {
    return fns.reduce((v, f) => f(v), x);
  };
}