JavaScript函数式编程实战:构建不可变数据流应用 | FP编程指南

2025-09-23 0 1,025

${TaskFilter({ filter: state.filter })}
${TaskList({
tasks: visibleTasks,
onToggleTask: id => this.store.dispatch(ActionCreators.toggleTask(id))
})}
${TaskInput({
onAddTask: text => this.store.dispatch(ActionCreators.addTask(text))
})}

`;
}

destroy() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
}

// 交互式函数式编程演示
document.addEventListener(‘DOMContentLoaded’, function() {
const demoSection = document.createElement(‘article’);
demoSection.innerHTML = `

函数式编程交互演示

不可变数据操作演示




`;
document.querySelector(‘main’).appendChild(demoSection);

// 演示函数
window.demoImmutableArray = function() {
const original = [1, 2, 3, 4];
const added = […original, 5];
const removed = original.filter(x => x !== 3);
const updated = original.map(x => x * 2);

const output = `
原始数组: [${original}]
添加元素后: [${added}]
删除元素3后: [${removed}]
所有元素乘以2: [${updated}]
原始数组未改变: [${original}]
`;
document.getElementById(‘demoOutput’).textContent = output;
};

window.demoFunctionComposition = function() {
const toUpper = str => str.toUpperCase();
const exclaim = str => str + ‘!’;
const repeat = str => str.repeat(2);

const process = pipe(toUpper, repeat, exclaim);
const result = process(‘hello’);

const output = `
函数组合演示:
输入: “hello”
处理流程: toUpper -> repeat -> exclaim
结果: “${result}”
`;
document.getElementById(‘demoOutput’).textContent = output;
};

window.demoCurrying = function() {
const add = a => b => c => a + b + c;
const add5 = add(5);
const add5And10 = add5(10);
const result = add5And10(15);

const output = `
柯里化演示:
const add = a => b => c => a + b + c;
const add5 = add(5);
const add5And10 = add5(10);
add5And10(15) = ${result}
`;
document.getElementById(‘demoOutput’).textContent = output;
};
});

// 工具函数定义
function pipe(…fns) {
return x => fns.reduce((v, f) => f(v), x);
}

JavaScript函数式编程实战:构建不可变数据流应用 | FP编程指南
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

淘吗网 javascript JavaScript函数式编程实战:构建不可变数据流应用 | FP编程指南 https://www.taomawang.com/web/javascript/1102.html

常见问题

相关文章

猜你喜欢
发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务