当前位置:网站首页>手写柯里化 - toString 理解
手写柯里化 - toString 理解
2022-08-05 09:14:00 【InfoQ】
let arr = []
function addCurry() {
let arg = Array.prototype.slice.call(arguments); // 收集参数
arr = arr.concat(arg);
if (arg.length === 0) { // 如果参数为空,则判断递归结束
return arr.reduce((a,b)=>{return a+b}) // 求和
} else {
return addCurry;
}
}
addCurry(1)(2)(3)() // 6
Array.prototype.slice.call(arguments)arrreduce()addCurry(1)(2)(3)() // 6
addCurry(1)() // 7
function addCurry() {
let arr = [...arguments]
let fn = function () {
if(arguments.length === 0) {
return arr.reduce((a, b) => a + b)
} else {
arr.push(...arguments)
return fn
}
}
return fn
}
addCurry(1)(2)(3)
//或
addCurry(1)(2,3)
toStringlet fn = function(){}
fn.toString = () => 1
fn == 1 // true
function addCurry() {
let arr = [...arguments]
// 利用闭包的特性收集所有参数值
var fn = function() {
arr.push(...arguments);
return fn;
};
// 利用 toString 隐式转换
fn.toString = function () {
return arr.reduce(function (a, b) {
return a + b;
});
}
return fn;
}
addCurry(1)(2)(3) == 6 // true
边栏推荐
猜你喜欢

2022.8.3

百行代码发射红心,程序员何愁命不中女朋友!

轩辕实验室丨欧盟EVITA项目预研 第一章(四)

Hundred lines of code launch red hearts, why programmers lose their girlfriends!

施一公:科学需要想象,想象来自阅读

pytorch余弦退火学习率CosineAnnealingLR的使用

嵌入式实操----基于RT1170 移植memtester做SDRAM测试(二十五)

画法几何及工程制图考试卷A卷

Example of Noise Calculation for Amplifier OPA855

链表中的数字相加----链表专题
随机推荐
Walk 100 trick society
无题四
Luogu P3368: 【模板】树状数组 2
How to replace colors in ps, self-study ps software photoshop2022, replace one color of a picture in ps with another color
好资料汇总
欧盟 | 地平线 2020 ENSEMBLE:D2.13 SOTIF Safety Concept(下)
2.4G无线收发模块的应用
tensorflow.keras cannot introduce layers
How ali cloud storage database automatically to speed up the loading speed of www.cxsdkt.cn how to set up the case?
Concurrent CAS
Dry goods!Generative Model Evaluation and Diagnosis
歌词整理
工程制图试题
PAT Level B - B1021 Single Digit Statistics (15)
PAT乙级-B1020 月饼(25)
ECCV 2022 Oral Video Instance Segmentation New SOTA: SeqFormer & IDOL and CVPR 2022 Video Instance Segmentation Competition Champion Scheme...
C语言-数组
The Secrets of the Six-Year Team Leader | The Eight Most Important Soft Skills of Programmers
2022/8/4 考试总结
CCVR eases heterogeneous federated learning based on classifier calibration