Trie endpoint:NODEJS

PHOTO EMBED

Fri Mar 03 2023 18:09:12 GMT+0000 (Coordinated Universal Time)

Saved by @mtommasi

class TrieNode {
  constructor(char) {
    this.char = char;
    this.isEndOfWord = false;
    this.children = {};
  }
}

class EndpointTrie {
  constructor() {
    this.root = new TrieNode(null);
  }

  insert(path, endpoint) {
    let node = this.root;

    for (const char of path) {
      if (!node.children[char]) {
        node.children[char] = new TrieNode(char);
      }
      node = node.children[char];
    }

    node.isEndOfWord = true;
    node.endpoint = endpoint;
  }

  find(path) {
    let node = this.root;

    for (const char of path) {
      if (!node.children[char]) {
        return null;
      }
      node = node.children[char];
    }

    if (node.isEndOfWord) {
      return node.endpoint;
    }

    return null;
  }
}
content_copyCOPY