0

I'm having trouble getting writing the getter method of my hash class based on what I have in the setter class.

The error I'm getting is: error: Uncaught TypeError: Cannot read property '1' of undefined

setItem = (key, value, value2) => {
    const idx = HashStringToInt(key, this.table.length);
    if (this.table[idx]) {
        this.table.push([key,[value, value2]]);
    } else {
        this.table[idx] = [[key, [value, value2]]]
    }        
}

getItem = key => {
    const idx = HashStringToInt(key, this.table.length);

    if (!this.table[idx]) {
        return null;
    }
    return this.table[idx].find(x => x[0] === key)[1]; //this doesn't work
}
6
  • 1
    If you pass this.table.length to your hash function and you keep changing the length, how are you expected to receive the same hashas before and after adding an item? Commented Jan 26, 2021 at 7:55
  • I see what you're saying, but how then can I write this to essentially have a key go to two values a = b,c ? Commented Jan 26, 2021 at 8:12
  • 1
    If you want two values per key, then a bog standard hash table where you store arrays of two items seems enough. The problem here isn't the number of values but that the hashing is unstable - after you push to the array any future hash recalculations will take the new length of the array. I don't know your hashing implementation but it seems a reasonable assumption that HashStringToInt("foo", 1) and HashStringToint("foo", 2) will produce different results. You can remedy that by using a constant size of the array, so the hash identity of the same key is stable. Commented Jan 26, 2021 at 8:18
  • In addition to hashing problems, isn't the if statement in setItem flipped around? If a given key exists, then a new item is pushed to the array, if it doesn't exist, then a key is overwritten. Commented Jan 26, 2021 at 8:19
  • thanks for the input but I seemed to have got it to do what I wanted now Commented Jan 26, 2021 at 8:23

1 Answer 1

1

Changing:

this.table.push([key,[value, value2]]);

To:

this.table[idx].push([key,[value, value2]]);

Seems to give me the desired results

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.