특징

구조

class Node {
  constructor(value = '') {
    this.value = value;
    this.children = new Map();
  }
}

class Trie {
  constructor() {
    this.root = new Node();
  }

  insert(string) {
    let currentNode = this.root;

    for (const char of string) {
      if (!currentNode.children.has(char)) {
        currentNode.children.set(char, new Node(currentNode.value + char));
      }
      currentNode = currentNode.children.get(char);
    }
  }

  has(string) {
    let currentNode = this.root;
    for (const char of string) {
      if (!currentNode.children.has(char)) return false;
      currentNode = currentNode.children.get(char);
    }
    return true;
  }
}

const trie = new Trie();
trie.insert('cat');
trie.insert('dog');
console.log(trie.has('c'));//true
console.log(trie.has('ca'));//true
console.log(trie.has('cat'));//true
console.log(trie.has('cag'));//false

console.log(trie.has('d'));//true
console.log(trie.has('do'));//true
console.log(trie.has('dog'));//true
console.log(trie.has('dot'));//false