Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chenshuhong opened this issue Aug 24, 2019 · 4 comments
Open

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

chenshuhong opened this issue Aug 24, 2019 · 4 comments
Labels

Comments

@chenshuhong
Copy link
Owner

chenshuhong commented Aug 24, 2019

柯里化

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

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
Copy link
Owner Author

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

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

@chenshuhong
Copy link
Owner Author

chenshuhong commented Aug 24, 2019

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

var foo = function() {
    var t = new Date();
    foo = function() {
        return t;
    };
    return foo();
};

@chenshuhong chenshuhong added the js label Aug 26, 2019
@chenshuhong
Copy link
Owner Author

chenshuhong commented Aug 26, 2019

函数组合

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
Copy link
Owner Author

记忆函数

// 第二版 (来自 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;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant