UNPKG

react-predictive-text

Version:
58 lines (51 loc) 1.76 kB
class Trie { constructor() { this.storage = {}; } add(word) { var currentStorage = this.storage; word.split("").forEach((letter) => { if (!currentStorage[letter]) { // if letter does not exist at current level currentStorage[letter] = {} //add it. } currentStorage = currentStorage[letter] // navigate to letter's storage. }); } retrieve(fragment) { var possibleWords = []; var currentStorage = this.storage; fragment.split("").forEach((letter) => { if (!currentStorage) { //if nothing in storage return null; //break out of forEach loop. } else { // else let uc = letter.toUpperCase(); let lc = letter.toLowerCase(); currentStorage = currentStorage[lc] || currentStorage[uc] // navigate to letter's storage. } }) // now we are at common storage for the fragment. So we just need to //Generate possible words. function generateWords(currentWord, storage) { if(!storage) return; // if storage is undefined then there are no possibilities left. if (Object.keys(storage).length === 0) {//if storage is empty //we are done with the word, so push it to possibleWords. possibleWords.push(currentWord); } else {//otherwise, //for each key in the storage for (var key in storage) { //add key to currentWord currentWord += key; //recurse using currentWord and the new storage. generateWords(currentWord, storage[key]) //remove key from currentWord so it won't be added next pass. currentWord = currentWord.split('').slice(0, currentWord.length-1).join(''); } } } generateWords(fragment, currentStorage); return possibleWords; } show() { console.log(this.storage); } } module.exports = Trie;