I’m currently going through book Eloquent JS and I can’t understand this code below:
function tableFor(event, journal) {
let table = [0, 0, 0, 0];
for (let i = 0; i < journal.length; i++) {
let entry = journal[i], index = 0;
if (entry.events.includes(event)) index += 1;
if (entry.squirrel) index += 2;
table[index] += 1;
}
return table;
}
console.log(tableFor("pizza", JOURNAL));
// → [76, 9, 4, 1]
You can look up JOURNAL here: https://eloquentjavascript.net/code/#4
And chapter here: https://eloquentjavascript.net/04_data.html - Computing correlation
Particularly I can’t understand this line
let entry = journal[i], index = 0;
I know that we reassign every object of the journal to entry, but what index=0 does? And every other index:
index += 2;
table[index] += 1;
The function first initializes that table array with four zeros. Note also that the possible values for index on each iteration of that loop are:
Those four values will act as indexes into the table. Each iteration of the loop adds one to one of the four table cells, so when the loop is finished the table contains counts of each of those different kinds of entries.
Oh, and at the top of the loop
let entry = journal[i], index = 0;
that's just a declaration of entry and index.
let entry = journal[i], index = 0
is shorthand for
let entry = journal[i];
let index = 0;
it works similarly for var, const and global declarations:
var entry = journal[i], index = 0
would translate to
var entry = journal[i];
var index = 0;
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