Skip to content

手写组合函数 #22

@Hongbusi

Description

@Hongbusi
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))

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions