1
var StreamChecker = function (words) {3
this.suffixLink = null; //this is where it will fallback to when a letter can't be matched4
this.id = -1; //this id will be 0 or greater if it matches a word5
this.next = new Map(); //map of <char, Trie*>7
this.root = new Trie();8
this.uniqueIds = 0; //used to count all the unique words discovered and as part of the Trie id system10
//standard trie traversal but keeping track of new words via id system11
for (const word of words) {13
for (const c of word) {14
if (!ptr.next.has(c)) {15
ptr.next.set(c, new Trie());17
ptr = ptr.next.get(c);20
ptr.id = this.uniqueIds++;24
//BFS traversal to build the automaton26
for (const [c, node] of this.root.next) {27
//all first level children should point back to the root when a match to a character fails28
node.suffixLink = this.root;33
const curr = q.shift();34
for (const [c, node] of curr.next) {35
let ptr = curr.suffixLink;36
while (ptr !== this.root && !ptr.next.has(c)) {39
//find the next suffixLink if it matches the current character or fallback to the root40
node.suffixLink = ptr.next.get(c) ?? this.root;42
//if the current suffixLink happens to also be a word we should store its id to make it quick to find43
if (node.suffixLink.id !== -1) {44
node.id = node.suffixLink.id;49
//the query ptr will now track every new streamed character and use it to match50
this.queryPtr = this.root;53
StreamChecker.prototype.query = function (letter) {54
//the query ptr will now track every new streamed character and can be used to quickly find words55
while (this.queryPtr !== this.root && !this.queryPtr.next.has(letter)) {56
this.queryPtr = this.queryPtr.suffixLink;58
this.queryPtr = this.queryPtr.next.get(letter) ?? this.root;59
//if any word is found it will have an id that isn't -160
return this.queryPtr.id !== -1;