tags: #js #javascript #data-structure #trie #toy-example #example ## trie.js ```js class Trie { constructor() { this.d = new Map() } insert(k,v) { if( k.length === 0 ) { this.data = v return } const c = k[0] if( ! this.d.has(c) ) { this.d.set(c,new Trie()) } return this.d.get(c).insert(k.slice(1),v) } remove(k) { // blatant memory leak but // our intention for this structure // is that we populate it at page load // and then no longer modify it. // so this function shouldn't really // even be here const node = this.getNode(k) if( node.data !== undefined ) { node.data = undefined } } has(k) { const node = this.getNode(k) if( node.data !== undefined ) return true return false } get(k) { const node = this.getNode(k) return node?.data } getNode(k) { // inefficient recursive approach if( k.length === 0 ) return this const c = k[0] if( !this.d.has(c) ) return undefined return this.d.get(c).getNode(k.slice(1)) } } ``` ## Test runner ```html