Is there a record log for the werewolf in the book "Articulate Coding: The Lycanthrope's

I've been tackling the challenges of Eloquent JavaScript at the Lycanthrope's Log, but I'm struggling to grasp a particular code snippet. Despite my efforts in checking values and testing with console.log, this piece of code still eludes me:

var JOURNAL = [
  {"events":["carrot","exercise","weekend"],"squirrel":false},
  {"events":["bread","pudding","brushed teeth","weekend","touched tree"],"squirrel":false},
  {"events":["carrot","nachos","brushed teeth","cycling","weekend"],"squirrel":false},
  // ...
]

function hasEvent(event, entry) {
  return entry.events.indexOf(event) != -1; // verifying if event occurred or not 
}

function tableFor(event, journal) {
  var table = [0, 0, 0, 0];
  for (var i = 0; i < journal.length; i++) {
   var entry = journal[i], index = 0;

   if (hasEvent(event, entry)) index += 1; // adding +1 to index if pizza happened
    //object of arrays --> console.log(entry); 
   if (entry.squirrel) index += 2; // increasing index by 2 if squirrel is true
   table[index] += 1; //<<-- This part is puzzling me 
   // console.log(index);
  }
 return table;
}

console.log(tableFor("pizza", JOURNAL));
// How are these values being calculated and added on indexes? Can someone help clarify this program for me?

If anyone can shed some light on how the values are processed and inserted into the array indexes, I would greatly appreciate it.

Answer №1

When we dive into each item from the JOURNAL collection, the table indexes signify specific scenarios:

  • table[0] increments by +1 if the event is absent in item.events and squirrel: false
  • table[1] increments by +1 if the event is present in item.events and squirrel: false
  • table[2] increments by +1 if the event is absent in item.events and squirrel: true
  • table[3] increments by +1 if the event is present in item.events and squirrel: true

Essentially, this table tracks different combinations of the squirrel and pizza variables. Ultimately, the table is utilized in the phi function to compute the correlation between these variables.

It's worth noting that utilizing the suggested formula for phi could simplify the process by transforming the table into a 2x2 matrix with entries like

table[0][0], table[0][1], table[1][0], and table[1][1]
, where rows denote the squirrel's state and columns indicate the presence of pizza in item.events.

Answer №2

According to the explanation in Eloquent Javascript, the journal/log contains around 90 entries JOURNAL.length

function tableFor(event, journal) {
  var table = [0, 0, 0, 0];

//A table with 4 figures is declared here for future incrementation,
  for (var i = 0; i < journal.length; i++) {
   var entry = journal[i], index = 0;

//A loop for journal.length initialization

Keep in mind that JOURNAL.length = 90, so this loop will iterate 90 times.

The first iteration of this loop sets i = 0 , and

journal[i] = {"events":["carrot","exercise","weekend"],"squirrel":false}
, index = 0 while checking for "pizza"

if (hasEvent(event, entry)) index += 1; 

//When this if statement in the loop evaluates, if(hasEvent(event, entry)) returns False, hence index = 0
if (entry.squirrel) index += 2;

//Moving forward in the loop, the entry.squirrel value being False results in no increment,
//So, the index remains at 0.

//NOTE: The increment pertains to the 'index' variable, not the 'table index'.
//At this point before the following code line, index still equals 0 (for the initial journal[i] where i=0)
//Since this is the first cycle (i=0), table remains [0,0,0,0]

 table[index] += 1; 

//Considering table[index] as table[0] which by now equals 0,
//Performing table[index] = table[index] + 1 equates to table[index]= 0+1.
//Updating table[index] += 0 where index = 0 leads to adding 1 to the first item in the table array.

//With this step, the table status shifts to [1, 0, 0, 0] but there are 89 more cycles to go.
  }

//Upon completion of all iterations, table becomes [76, 9, 4, 1]
 return table;
}

In the code you provided, JOURNAL holds only 3 entries, therefore

console.log(tableFor("pizza", JOURNAL))
Outputs: table = [3, 0, 0, 0];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Establishing a limit on the maximum number of classes that can be selected/activated when clicking on multiple divs or IDs

Working on a talent tree, I encountered an interesting issue. Currently, the code allows users to select up to 4 talents. However, when duplicating the talent tree for a second hero or party member, the same limit is shared across all trees. Attempts have ...

Ensure that all values are equal before continuing to run the function within each jQuery function

When the provided code is executed, it checks if any of the input values do not match the attribute value. If a mismatch is found, it returns false and does not call the function "printDiv()", which is used for window printing. However, an error alert mess ...

Submitting a form via NextJS to an internal API

After reading through the Next.JS documentation, I came across an interesting point. Note: Instead of using fetch() to call an API route in getStaticProps, it's recommended to directly import the logic from within your API route and make necessary cod ...

Retrieve a file through a POST request with node.js

Hi everyone, I'm trying to create a "export to excel" functionality in Node.js for a page. By using Chrome DevTools, I discovered that the file is downloaded after a post request, so I need to replicate it. https://i.sstatic.net/aL9SO.png var reques ...

Reorganize the data in a different manner (collections of items instead of individual items linked to groups)

Is there a way to create a function that converts data from `DevicesType` to `GroupsType` below? Instead of having a list of devices showing the groups they belong to, I need a list of groups with their respective devices. type DevicesType = { id: string ...

provide the key and id to a node.js module

Currently, I am utilizing the Express framework to establish a module for handling requests to a third-party API. This particular API necessitates an ID and key to be transmitted. Rather than embedding these credentials directly into the module, I prefer ...

Modifying modal content disrupts AJAX events

When using jquery-ujs for ajax requests with data-remote="true", I encounter an issue where the first request goes smoothly but subsequent ones break. It seems that when certain events like $('#modal').empty(), $('#modal').tex ...

Transforming a decimal number into binary base 2 manually in Javascript without using pre-defined functions

As a newcomer to coding and Javascript, I have been given an assignment that requires me to convert base 10 numbers to binary without using specific built-in methods in Javascript (such as alert(a.toString(16))). The constraints are that I can only use loo ...

What is the best way to paginate aggregated results in Mongoose?

In my project, I have a User model that is linked to two other associated models - Profile and WorkProfile. The Profile model contains basic information about the user like name, email, and home address, while the WorkProfile model stores details such as o ...

Issue with two Jquery slider forms

Within a Jquery slider, I have implemented two distinct forms (using this specific Jquery slider: http://tympanus.net/Tutorials/FancySlidingForm/) . My goal now is to establish JavaScript/jQuery validation for these two forms separately BASED on the form ...

Ways to make a webpage automatically adjust its layout using pixels and incorporating rems

Using rem units allows for easy control of full page size to make it responsive. For example: div{ font-size:20rem; } @media only screen and (max-width: 576px) { html{ font-size:20%; } } But what can we do when using px units instead ...

Increasing the number of controller methods in Angular

Within AngularJs, I have multiple controllers that share similar functions: angular.module('myApp').controller(...){ function lockForm(id){ ... } function releaseForm(id){ ... } function dbError(e){ ...

Challenge with neglected open connections from a comet

Utilizing various comet techniques like long polling and forever frame, along with iframes for cross subdomain activities, has presented a challenge during implementation. When a user refreshes the page or navigates to another page, a new request is made w ...

Implementing a 1-second delay in a Vue.js delete request

I have items that are retrieved through API calls and users can add them to their cart. They also have the option to delete items from the cart, but I want the item to be visually removed from the front-end after 1 second because of an animation on the del ...

Developing an Angular template component integrated with Express JS backend

I'm encountering an issue while attempting to load a template file from one of my folders in Angular. I have my JS files statically called with Express, however, the template files are not loading. I have tried placing them in the views folder along w ...

How can we effectively reroute HTTP requests according to the information stored in a database?

When operating an express server, what is the appropriate method for redirecting incoming requests? In my application, I have two routes: POST and UPDATE. The POST route is responsible for creating a new item in the database, while the UPDATE route increa ...

Ways to achieve 8 columns in a single row using Javascript and Bootstrap

Recently, I created a simple function for searching movies and manipulating them in the DOM. The issue arises when a movie name is entered and the API response returns around 20-30 recommendations. I wanted to display this fetched data in 8 columns per row ...

The functionality of a button within an AngularJS directive is not functioning as intended

I am trying to use a directive twice on one page. Inside the directive, there is a button that should toggle between showing the two directives when clicked. However, I'm encountering an issue where the values are not changing even though the ng-click ...

Collection of clickable images that lead to creatively designed individual pages

Being relatively new to JavaScript and jQuery, my knowledge is solid when it comes to HTML & CSS. Currently, I have a page with 20 minimized pictures (with plans to increase to 500+ images) that open into a new page when clicked. Although I have no issues ...

Exploring the power of Jade and Angular through implementing a for loop within a table structure

I'm brand new to using Jade and Angular, and I could really use a hint from someone more experienced. ... - for (var i = 0; i < p.length; i++) tr td= i + 1 td= price(value='p[i].somedbstuff') ... I want the la ...