面试题:写一个函数柯里化

80 阅读1分钟

1.什么是函数柯里化?

柯里化函数(Currying)是一种高阶函数技术,它将一个接受多个参数的函数转换为一系列函数,每个函数都接受一个单一参数,并返回一个新函数以处理剩余的参数。

1.柯里化函数:第一个参数一定是函数,传入其他固定参数

  //求:(2+3)*5 , (2+5)*6 ,(2+4)*7 , (2+4)*16
  /**
   *将一个接受多个参数的函数fn转换为一系列函数,
   *每个函数fn都接受一个单一参数2
   *并返回一个新函数以处理剩余的参数
   */

class curryFn {
    curry(func) {
      //柯里化函数
      const args = Array.prototype.slice.call(arguments, 1);

      const _this = this;
      return function () {
        const curArgs = Array.from(arguments);
        const totalArgs = [...args, ...curArgs];
        if (totalArgs.length >= func.length) {
          //参数数量够了
          return func.apply(null, totalArgs);
        } else {
          //参数数量不够
          totalArgs.unshift(func);
          return _this.curry.apply(_this, totalArgs);
        }
      };
    }
  }

  function fn(x, y, z) {
    return (x + y) * z;
  }
  let myPlugin = new curryFn();

  //第一个参数一定是函数,传入其他固定参数
  var xFn = myPlugin.curry(fn, 2);
  const res1 = xFn(3, 5);
  const res2 = xFn(5, 6);
  console.log(res1); //25
  console.log(res2); //42

  const yfn = xFn(4);
  const res3 = yfn(7);
  const res4 = yfn(16);
  console.log(res3); //49
  console.log(res4); //96

2.重点剖析柯里化函数的日常使用场景

class curryFn {
    curry(func) {
      //柯里化函数
      const args = Array.prototype.slice.call(arguments, 1);

      const _this = this;
      return function () {
        const curArgs = Array.from(arguments);
        const totalArgs = [...args, ...curArgs];
        if (totalArgs.length >= func.length) {
          //参数数量够了
          return func.apply(null, totalArgs);
        } else {
          //参数数量不够
          totalArgs.unshift(func);
          return _this.curry.apply(_this, totalArgs);
        }
      };
    }
}

function createElementFn(container,name,props,styles,content){
    const ele=document.createElement(name)
    container.appendChild(ele)
    for(const prop in props){
      ele[prop]=props[prop]
    }
    for(const prop in styles){
      ele.style[prop]=styles[prop]
    }
    ele.innerHTML=content
}
  let myPlugin = new curryFn();
  const container=document.getElementById('container')

 //第一个参数一定是函数,传入其他固定参数
  const elefn=myPlugin.curry(createElementFn,container,'div',{class:'box'},{width:'600px',height:'200px',background:'red',marginBottom:'10px'})

  elefn('内容1')
  elefn('内容2')