Memory-efficient structures — minimize memory usage.
1// Trie for string storage2class Trie {3 constructor() {4 this.root = {};5 }67 insert(word) {8 let node = this.root;9 for (const char of word) {10 if (!node[char]) node[char] = {};11 node = node[char];12 }13 node.isEnd = true;14 }1516 search(word) {17 let node = this.root;18 for (const char of word) {19 if (!node[char]) return false;20 node = node[char];21 }22 return node.isEnd === true;23 }2425 startsWith(prefix) {26 let node = this.root;27 for (const char of prefix) {28 if (!node[char]) return false;29 node = node[char];30 }31 return true;32 }33}3435// Compact array for small integers36class CompactArray {37 constructor(maxValue) {38 this.bitsPerElement = Math.ceil(Math.log2(maxValue + 1));39 this.bytesPerElement = Math.ceil(this.bitsPerElement / 8);40 }4142 encode(arr) {43 const buffer = Buffer.alloc(arr.length * this.bytesPerElement);44 arr.forEach((val, i) => {45 buffer.writeUIntLE(val, i * this.bytesPerElement, this.bytesPerElement);46 });47 return buffer;48 }4950 decode(buffer) {51 const arr = [];52 for (let i = 0; i < buffer.length; i += this.bytesPerElement) {53 arr.push(buffer.readUIntLE(i, this.bytesPerElement));54 }55 return arr;56 }57}5859// Usage60const trie = new Trie();61trie.insert("hello");62trie.insert("world");63console.log(trie.search("hello")); // true64console.log(trie.startsWith("wor")); // true