Skip to content

手写组合函数 #22

Open
Open

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

Activity

  1. ChenHaoJie9527 commented on Jun 27, 2022

    @ChenHaoJie9527

    组合函数-简单版

    // 简单实现组合函数
    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']));
  2. luckept commented on Jun 27, 2022

    @luckept
    Member

    不知道理解得对不对

    function compose(...fns) {
      let res
      return function(...args) {
        fns.forEach((fn) => {
          if (!res) {
            res = fn(...args)
          } else {
            res = fn(res)
          }
        })
        return res
      }
    }
  3. myltx commented on Jun 29, 2022

    @myltx

    这样的也可以达到效果

    /**
     * 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

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