JavaScript Data structures: The Final Analysis

We need to compute a correlation for every type of event that occurs in the data set. To do that, we first need to find every type of event.

function journalEvents(journal) {

let events = []; for (let entry of journal) {

for (let event of entry.events) {

if (!events.includes(event)) {

events.push(event);

}

}

}

return events;

} console.log(journalEvents(JOURNAL));

// → [“carrot”, “exercise”, “weekend”, “bread”, …]

By going over all the events and adding those that aren’t already in there to the events array, the function collects every type of event.

Using that, we can see all the correlations.

for (let event of journalEvents(JOURNAL)) {

console.log(event + “:”, phi(tableFor(event, JOURNAL)));

}

// → carrot:   0.0140970969

// → exercise: 0.0685994341

// → weekend:  0.1371988681

// → bread:    -0.0757554019

// → pudding:  -0.0648203724

// and so on…

Most correlations seem to lie close to zero. Eating carrots, bread, or pudding apparently does not trigger squirrel-lycanthropy. It does seem to occur somewhat more often on weekends. Let’s filter the results to show only correlations greater than 0.1 or less than -0.1.

Aha! There are two factors with a correlation that’s clearly stronger than the others. Eating peanuts has a strong positive effect on the chance of turning into a squirrel, whereas brushing his teeth has a significant negative effect.

Interesting. Let’s try something.

for (let entry of JOURNAL) {

if (entry.events.includes(“peanuts”) &&

!entry.events.includes(“brushed teeth”)) {

entry.events.push(“peanut teeth”);

}

}

console.log(phi(tableFor(“peanut teeth”, JOURNAL))); // → 1

That’s a strong result. The phenomenon occurs precisely when Jacques eats peanuts and fails to brush his teeth. If only he weren’t such a slob about dental hygiene, he’d have never even noticed his affliction.

Knowing this, Jacques stops eating peanuts altogether and finds that his transformations don’t come back.

For a few years, things go great for Jacques. But at some point he loses hisjob. Because he lives in a nasty country where having no job means hav­ing no medical services, he is forced to take employment with a circus where he performs as The Incredible Squirrelman, stuffing his mouth with peanut butter before every show.

One day, fed up with this pitiful existence, Jacques fails to change back into his human form, hops through a crack in the circus tent, and vanishes into the forest. He is never seen again.

Source: Haverbeke Marijn (2018), Eloquent JavaScript: A Modern Introduction to Programming,

No Starch Press; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *