We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
实现一个聚合函数
sum(1,2,3).sumOf() // 6 sum(1)(2,3,4)(6).sumOf() // 16
结果如下:
function sum(...arg){ const nums = [...arg] const pushArg = function(...arg){ nums.push(...arg) return pushArg } pushArg.sumOf = function(){ return nums.reduce((pre,now)=>{ return pre + now },0) } return pushArg }
其实了解js的函数柯里化的话,这个题很好解决:
函数柯里化以Haskell Brooks Curry命名,柯里化是指将一个函数分解为一系列函数的过程,每个函数都只接收一个参数。(译注:这些函数不会立即求值,而是通过闭包的方式把传入的参数保存起来,直到真正需要的时候才会求值)
柯里化有3个常见作用:
上面的那个题就是属于延迟计算/运行一个常见场景
var action= function(action) { var doing = function(doing) { var result = ""; if (action === "action1") { if (doing === "doing1") { result = "doing1"; } else if (doing === "doing2") { result = "doing2"; } } else { if (doing === "doing3") { result = "doing3"; } else if (doing === "doing4") { result = "doing4"; } } console.log(result); return doing }; return doing; }; action("action1")("doing1")("doing2");
参数 action1 是action函数使用的,接下来的doing1、doing2都是内部doing函数使用;这个时候有个概念大家一定要知道关于闭包的感念;不懂的可以试下去看看
action
doing
// 正常正则验证字符串 reg.test(txt) // 函数封装后 function check(reg, txt) { return reg.test(txt) } check(/\d+/g, 'test') //false check(/[a-z]+/g, 'test') //true // Currying后 function curryingCheck(reg) { return function(txt) { return reg.test(txt) } } var hasNumber = curryingCheck(/\d+/g) var hasLetter = curryingCheck(/[a-z]+/g) hasNumber('test1') // true hasNumber('testtest') // false hasLetter('21212') // false
The text was updated successfully, but these errors were encountered:
No branches or pull requests
实现一个聚合函数
结果如下:
其实了解js的函数柯里化的话,这个题很好解决:
柯里化有3个常见作用:
上面的那个题就是属于延迟计算/运行一个常见场景
提前返回
参数 action1 是
action
函数使用的,接下来的doing1、doing2都是内部doing
函数使用;这个时候有个概念大家一定要知道关于闭包的感念;不懂的可以试下去看看参数复用
The text was updated successfully, but these errors were encountered: