Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写组合函数 #22

Open
Hongbusi opened this issue Jun 27, 2022 · 3 comments
Open

手写组合函数 #22

Hongbusi opened this issue Jun 27, 2022 · 3 comments
Labels

Comments

@Hongbusi
Copy link
Member

Hongbusi commented Jun 27, 2022

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))
@Hongbusi Hongbusi added handwritten-code today 每日一题。 JS javascript labels Jun 27, 2022
@ChenHaoJie9527
Copy link

组合函数-简单版

// 简单实现组合函数
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
Copy link
Member

luckept commented Jun 27, 2022

不知道理解得对不对

function compose(...fns) {
  let res
  return function(...args) {
    fns.forEach((fn) => {
      if (!res) {
        res = fn(...args)
      } else {
        res = fn(res)
      }
    })
    return res
  }
}

@Hongbusi Hongbusi removed the today 每日一题。 label Jun 28, 2022
@myltx
Copy link

myltx commented Jun 29, 2022

这样的也可以达到效果

/**
 * 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);
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

4 participants