I am a newbie reading about functional thinking in javascript these days. My background is mostly OOP in Java/Ruby.
Suppose I want to get user input in node, I could do it as :
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);
I am maintaining explicit state here. What is the functional way to achieve the same thing?
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);