Home > Net >  Getting undefined using new Map() in Class for counting occurences in array
Getting undefined using new Map() in Class for counting occurences in array

Time:06-23

I keep getting undefined with this class, please someone help me! i have tried adding this.something to almost everything in the constructor, which shouldn't be neccesary and it still doesnt work (no big surprise there...), would really appreciate some help!

class Counter {
  constructor(text) {
    // TODO: build an internal Map of word => occurrences.
    this.text = text;
    const textArray = this.text.split(" ");
    const count = {};
    for (const word of textArray) {
      if (count[word]) {
        count[word]  = 1;
      } else {
        count[word] = 1;
      }
    }
    this.map1 = new Map();
    for (const word of textArray) {
      this.map1.set(word, count[word]);
    }

  }


  occurrences(word) {
    // TODO: return the number of occurrences
    return this.map1.get(word);
  }
}

error:

Should be case-insensitive

    expect(received).toBe(expected)
    
    Expected value to be (using ===):
      1
    Received:
      undefined
    
    Difference:
    
      Comparing two different types of values. Expected number but received undefined.
      
      at Object.<anonymous> (__tests__/01_counter.test.js:9:40)
          at new Promise (<anonymous>)
      at processTicksAndRejections (internal/process/task_queues.js:93:5

and this is the test:

test("Should be case-insensitive", () => {
  const counter = new Counter("Lorem ipsum dolor sit amet, consectetur adipisicing elit");
  expect(counter.occurrences("lorem")).toBe(1);
});

CodePudding user response:

If the key doesn't exist in the map, occurrences() needs to return 0, because get() will return undefined.

  occurrences(word) {
    // TODO: return the number of occurrences
    return this.map1.get(word) || 0;
  }

CodePudding user response:

If there is no key "hello" in Map, then this.map1.get("hello") will return undefined, not 0.

If you want to receive 0 in case there are no occurances, modify method

  occurrences(word) {
    // TODO: return the number of occurrences
    return this.map1.get(word) ?? 0;
  }

CodePudding user response:

The test case you've supplied requires the occurences() function to return 0 if it either does not find a match or the internal map is simply empty.

This can be done by returning 0 in case it can't find a match.

For example:

  occurrences(word) {
    let returnValue=this.map1.get(word)!=undefined ? this.map1.get(word) : 0;
    return returnValue;
  }

}

CodePudding user response:

it is working now!! it was what Barmar said, i just had to add the || 0 at the return in occurences method. very dumb mistake. Thanks to you all!

  • Related