Working on the stream-adventure NodeJS tutorial, but am struggling with the duplexer redux exercise.
This is what I've tried to use, but it doesn't work:
var duplexer = require('duplexer2');
var through = require('through2').obj;
module.exports = function (counter) {
var counts = {};
var input = through(write, end);
return duplexer(input, counter);
var write = function (row, _, next) {
counts[row.country] = (counts[row.country] || 0) + 1;
next();
}
var end = function (done) {
counter.setCounts(counts);
done();
}
};
This is the proposed solution, which works:
var duplexer = require('duplexer2');
var through = require('through2').obj;
module.exports = function (counter) {
var counts = {};
var input = through(write, end);
return duplexer(input, counter);
function write (row, _, next) {
counts[row.country] = (counts[row.country] || 0) + 1;
next();
}
function end (done) {
counter.setCounts(counts);
done();
}
};
Can someone help me understand the difference between using the anonymous function saved into a variable versus just naming a function?
The difference is hoisting. When you use a function declaration statement (i.e. what's being used in the proposed solution), its definition is "hoisted" to the top of the scope (read: function) that contains it, and therefore even if you try to reference it before the code that defines it, it will be available.
You are using a variable assignment to define your functions. This means that write will not have a value until the var write = statement executes. You are trying to use it before that, when write still has the value undefined.
What this means is that you can get your code to work simply by moving the location where you define your functions:
module.exports = function (counter) {
var counts = {};
var write = function (row, _, next) {
counts[row.country] = (counts[row.country] || 0) + 1;
next();
};
var end = function (done) {
counter.setCounts(counts);
done();
};
var input = through(write, end);
return duplexer(input, counter);
};
n.b. Do not confuse function declaration statements with named function expressions. named function expressions are unhoisted, just like anonymous functions:
var boom = getNumber();
var getNumber = function getNumber() { return 3; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With