Nit*_*eti 0 javascript functional-programming node.js
这些天我是关于javascript中的功能性思考的新手.我的背景主要是Java/Ruby中的OOP.
假设我想在节点中获取用户输入,我可以这样做:
process.stdin.resume();
process.stdin.setEncoding("ascii");
var input_buffer = "";
process.stdin.on("data", function (input) {
input_buffer += input;
});
function process_input()
{
// Process input_buffer here.
do_something_else();
}
function do_something_else()
{
}
process.stdin.on("end",process_input);
Run Code Online (Sandbox Code Playgroud)
我在这里保持明确的状态.实现同样的功能是什么?
所以一般来说,纯函数式程序员喜欢将它们的I/O代码保存在一个包含良好的小盒子里,这样他们就可以尽可能地集中精力编写接受内存数据类型作为参数和返回值的纯函数(或调用回调函数)有价值的).因此,考虑到这一点,基本思路是:
//Here's a pure function. Does no I/O. No side effects.
//No mutable data structures. Easy to test and mock.
function processSomeData(theData) {
//useful code here
return theData + " is now useful";
}
//Here's the "yucky" I/O kept in a small box with a heavy lid
function gatherInput(callback) {
var input = [];
process.stdin.on('data', function (chunk) {input.push(chunk);});
process.stdin.on('end', function () {callback(input.join('');});
}
//Here's the glue to make it all run together
gatherInput(processSomeData);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1264 次 |
| 最近记录: |