Search code examples
javascriptoopecmascript-6hashmapes6-class

How do I fix the error '.has is not a function' when using JavaScript Map?


I have the following code that attempts to set a value in a Map:

class Trie {
  constructor () {
    this.trie = new Map()
  }

  insert(word) {
    let current = this.trie
    for (let alpha of word) {
      if (!current.has(alpha)) current.set(alpha, [])
      current = current.get(alpha)
    }
    current.word = word
  }
}

let trie = new Trie()
trie.insert('test')
console.log(trie.trie)

When I attempt to run it, I get the error .has is not a function. What am I missing here?


Solution

  • You're reassigning current to a non-Map value inside the loop, so on subsequent iterations, current.has will not work. Sounds like you need to change the [] to a new Map instead.

    class Trie {
      constructor () {
        this.trie = new Map()
      }
    
      insert(word) {
        let current = this.trie
        for (let alpha of word) {
          if (!current.has(alpha)) current.set(alpha, new Map())
          current = current.get(alpha)
        }
        current.word = word
      }
    }
    
    let trie = new Trie()
    trie.insert('test')
    console.log([...trie.trie])

    enter image description here