1

This is my first post here. I have a little question. Code:

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; // Why +2?
        table[index] += 1;
    }
    return table;
}

console.log(tableFor("pizza", JOURNAL));
// → [76, 9, 4, 1]

The JOURNAL file can be found here.

My question is that why there is += index. When i run code, It gives me right results of course, but I don't understand why is +2 not +1? I see that +1 gives me wrong result.

Thanks for replying.

3 Answers 3

2

The table array output looks just like a conditional counter. It has 4 possible indexes, each of which increments depending on the events found in the current journal item.

By the look of your function the counters represent the following (given the following indexes):

0 - does not contain the given event or squirrel
1 - contains the given event but not squirrel
2 - contains squirrel but not the given event
3 - contains both the given event and squirrel

So to answer specifically, why += 2? Well, by adding 2 the index will end up being either 2 or 3, indicating one of the two conditions above.

Sign up to request clarification or add additional context in comments.

Comments

1

index appears to be a bitset. If you find pizza but no squirrel you get 0b01, if you have a squirrel but no pizza you get 0b10, if you find both you get 0b11 and for neither you get 0b00. The value for pizza, 21, needs to be distinguishable from the value for squirrel, 20, for that.

A cleaner code might have used bit operators:

const entry = journal[i];
const index = (entry.events.includes(event)) << 0) | (entry.squirrel << 1);
table[index] += 1;

Comments

0

If I recall correctly then the table indexes represent the following.

0: no pizza, no squirrel 
1: pizza, no squirrel
2: no pizza, squirrel
3: both

therefore if you want to target those indexes correctly then pizza gives +1 to the index position and squirrel adds +2 to the index position

  • if there is not pizza and no squirrel - `index = 0`
  • if there is pizza (`index +1`) and no squirrel - `index = 1`
  • if there is no pizza and squirrel (`index +2`) - `index = 2`
  • if there are both pizza (`index +1`) and squirrel (`index +2`) - `index = 3`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.