curry and bind

  • curry
/**
 * NOTE: 实现函数curry,该函数接受一个多元(多个参数)的函数作为参数,然后一个新的函数,
这个函数 可以一次执行,也可以分多次执行。
 */


/**
 * NOTE: curry 的意义在于能够在不完全指定函数参数的情况下运行函数,
实际意义呢? 其实curry需要和compose等配合来有效果,比如 配合写出{ pointfree: 不使用所要处理的值,只合成运算过程 }的代码。
 */

function curry(fn) {
  const ctx = this;
  function inner(...args) {
    // fn.lenght  === fn args length
    if (args.length === fn.length) {
      return fn.call(ctx, ...args);
    }
    return (...innerArgs) => inner.call(ctx, ...args, ...innerArgs);
  }

  return inner;
}

// test
function test(a, b, c) {
  console.log(a, b, c);
}

const f1 = curry(test)(1);
const f2 = f1(2);
console.log(f2(3))


  • bind
/**
 * NOTE: 写一个函数,实现Function.prototype.bind的功能。
 */

Function.prototype.myBind = function (ctx, ...args) {
  return (...innerArgs) => this.call(ctx, ...args, ...innerArgs);
}

// test
const a = {
  name: "name of a"
};
function test(...msg) {
  console.log(this.name);
  console.log(...msg);
}
const t = test.myBind(a, "hello");
t("world");



©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容