简体   繁体   中英

eloquent javascript chapter 4 array

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.

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.

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, 2 1 , needs to be distinguishable from the value for squirrel, 2 0 , 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;

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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM