|
| 1 | +const Node = require('./Node'); |
| 2 | + |
| 3 | +class Trie { |
| 4 | + constructor() { |
| 5 | + this.root = new Node(''); |
| 6 | + } |
| 7 | + |
| 8 | + // helper to get the index of a character |
| 9 | + // eslint-disable-next-line class-methods-use-this |
| 10 | + getIndexOfChar(char) { |
| 11 | + return char.charCodeAt(0) - 'a'.charCodeAt(0); |
| 12 | + } |
| 13 | + |
| 14 | + insert(key) { |
| 15 | + if (!key) { |
| 16 | + return false; |
| 17 | + } |
| 18 | + |
| 19 | + // convert to lower case |
| 20 | + // keys are basically words |
| 21 | + const word = key.toLowerCase(); |
| 22 | + let currentNode = this.root; |
| 23 | + |
| 24 | + for (let level = 0; level < word.length; level += 1) { |
| 25 | + const index = this.getIndexOfChar(word[level]); |
| 26 | + if (!currentNode.children[index]) { |
| 27 | + currentNode.children[index] = new Node(word[level]); |
| 28 | + } |
| 29 | + currentNode = currentNode.children[index]; |
| 30 | + } |
| 31 | + |
| 32 | + // when we are done with inserting all the character of the word, |
| 33 | + // mark the node as end leaf |
| 34 | + currentNode.markAsLeaf(); |
| 35 | + return true; |
| 36 | + } |
| 37 | + |
| 38 | + search(key) { |
| 39 | + if (!key) { |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + // convert word to lower case |
| 44 | + const word = key.toLowerCase(); |
| 45 | + let currentNode = this.root; |
| 46 | + |
| 47 | + for (let level = 0; level < word.length; level += 1) { |
| 48 | + const index = this.getIndexOfChar(word[level]); |
| 49 | + if (!currentNode.children[index]) { |
| 50 | + return false; |
| 51 | + } |
| 52 | + currentNode = currentNode.children[index]; |
| 53 | + } |
| 54 | + if (currentNode !== null && currentNode.isEndOfWord) { |
| 55 | + return true; |
| 56 | + } |
| 57 | + return false; |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// const words = ['bed', 'ball', 'apple', 'java', 'javascript']; |
| 62 | +// const trie = new Trie(); |
| 63 | + |
| 64 | +// words.forEach(word => trie.insert(word)); |
| 65 | + |
| 66 | +// console.log(trie.root); |
| 67 | + |
| 68 | +// console.log(trie.search(words[3])); |
| 69 | +// console.log(trie.search('word')); |
| 70 | +// console.log(trie.search(words[4])); |
| 71 | +// console.log(trie.search('random')); |
| 72 | + |
| 73 | +module.exports = Trie; |
0 commit comments