Created
March 13, 2017 13:38
-
-
Save hereisfun/b8204ae23c49154152c2850a93f8ad03 to your computer and use it in GitHub Desktop.
函数柯里化
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//将用于柯里化的函数本身最好能接受不定数量的参数 | |
//此处的闭包是本意主要是让plus函数在不currying的情况下也能照常工作 | |
var plus = (function(){ | |
var result = 0; | |
return function(){ | |
for(let i = 0; i < arguments.length; i++){ | |
result += arguments[i]; | |
} | |
return result; | |
} | |
})(); | |
var currying = function(fn){ | |
var cache = []; | |
return function curry(){ | |
var cresult = 0; | |
//无参数时,直接将缓存了的参数一次性推给fn | |
if(arguments.length === 0){ | |
cresult = fn.apply(this, cache); | |
// cache = []; | |
return cresult; | |
}else{ | |
[].push.apply(cache, arguments); | |
//这里返回curry是为了能让它能链式调用 | |
return curry; | |
} | |
} | |
} | |
var curriedPlus = currying(plus); | |
curriedPlus(1)(2)(3,4)(5); | |
console.log(curriedPlus()); | |
// curriedPlus(1)(2)(3,4)(5);//如果这里加上这两句会发生错误,输出结果本应是30但实际输出45 | |
// console.log(curriedPlus());//根本原因是原函数有闭包,保存了第一次计算的结果,而缓存同时也保存了全部的参数,结果导致加了两次 | |
//我的解决方案是在无参数调用后清空缓存队列,但这方法不够通用 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment