函数科里化
-
在函数式编程中,科里化最重要的是把多参函数变为单参函数
-
举个例子:我们创建一个通用函数来复用
// 实现科里化
Object.prototype.curry = function (func, ...args) {
const that = this;
// 得到从下标1开始的参数数组
return function (...curArgs) {
const totalArgs = [...args, ...curArgs];
if (totalArgs.length >= func.length) {
return func.apply(null, totalArgs);
} else {
totalArgs.unshift(func);
return that.curry.apply(that, totalArgs)
}
}
}
const plugins = new Object();
function createElement(container, name, props, styles, content) {
const ele = document.createElement(name);
container.appendChild(ele);
for (let prop in props) {
ele[prop] = props[prop]
}
for (let prop in styles) {
ele.style[prop] = styles[prop];
}
content && (ele.innerHTML = content);
}
const div = document.querySelector('.container');
// 使用科里化
const createDiv = plugins.curry(createElement, div, 'div', {}, { width: '100px', height: '100px', border: '1px solid red' })
createDiv('Hello1')
createDiv('Hello2')
createDiv('Hello3')
createDiv('Hello4')
本文作者:HuangBingQuan
本文链接:https://www.cnblogs.com/bingquan1/p/17659737.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步