chenshuhong / fullstack

我的全栈路线思维导图以及日常知识记录
MIT License
0 stars 0 forks source link

JavaScript函数系列骚操作系列 #9

Open chenshuhong opened 4 years ago

chenshuhong commented 4 years ago

柯里化

利用闭包把变量保存起来,知道参数足够再调用函数

function curry(fn, args) {
  var length = fn.length;
  args = args || [];
  return function() {
    var _args = args.slice(0),
      arg, i;
    for (i = 0; i < arguments.length; i++) {
      arg = arguments[i];
      _args.push(arg);
    }
    if (_args.length < length) {
      return curry.call(this, fn, _args);
    }
    else {
      return fn.apply(this, _args);
    }
  }
}
chenshuhong commented 4 years ago

偏函数 柯里化是偏函数的一种

function partial(fn) {
    var args = [].slice.call(arguments, 1);
    return function() {
        var newArgs = args.concat([].slice.call(arguments));
        return fn.apply(this, newArgs);
    };
};
chenshuhong commented 4 years ago

惰性函数 惰性函数就是解决每次都要进行判断的这个问题,解决原理很简单,重写函数。

var foo = function() {
    var t = new Date();
    foo = function() {
        return t;
    };
    return foo();
};
chenshuhong commented 4 years ago

函数组合

function compose() {
    var args = arguments;
    var start = args.length - 1;
    return function() {
        var i = start;
        var result = args[start].apply(this, arguments);
        while (i--) result = args[i].call(this, result);
        return result;
    };
};
function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}
chenshuhong commented 4 years ago

记忆函数

// 第二版 (来自 underscore 的实现)
var memoize = function(func, hasher) {
    var memoize = function(key) {
        var cache = memoize.cache;
        var address = '' + (hasher ? hasher.apply(this, arguments) : key);
        if (!cache[address]) {
            cache[address] = func.apply(this, arguments);
        }
        return cache[address];
    };
    memoize.cache = {};
    return memoize;
};