1

这些天,我是一个新手,正在阅读有关 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);

我在这里保持明确的状态。实现同一目标的功能性方式是什么?

4

1 回答 1

5
  1. Write pure functions for as much of your program as possible
    • No I/O, no side effects, no mutable data structures, etc
  2. Keep your I/O cleanly separate and organized

So in general purely functional programmers like to keep their I/O code in a well-contained and small box so they can focus as much as possible on writing pure functions that accept in-memory data types as arguments and return values (or invoke callbacks with values). So with that in mind, the basic idea is:

//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);
于 2013-06-10T21:57:43.553 回答