Created
June 28, 2018 17:44
-
-
Save felipediogo/2b41687101a51bb3ef655b265a56c5bb to your computer and use it in GitHub Desktop.
Implementation of trie (data structure) in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const input = 'feli'; | |
const input2 = 'fela'; | |
const head = {}; | |
const add = (s, node, index) => { | |
if (index === s.length) return; | |
const char = s[index]; | |
if (!!node[char]) { | |
node[char].size++; | |
} else { | |
node[char] = { | |
size: 1 | |
}; | |
} | |
add(s, node[char], ++index); | |
}; | |
const find = (s, node, index) => { | |
if (index === s.length) return node.size; | |
const char = s[index]; | |
if (!node[char]) return 0; | |
return find(s, node[char], ++index); | |
}; | |
add(input, head, 0); | |
add(input2, head, 0); | |
console.log(JSON.stringify(head)); | |
console.log(find('fel', head, 0)); | |
console.log(find('fela', head, 0)); | |
console.log(find('feli', head, 0)); | |
console.log(find('fel1', head, 0)); | |
console.log(find('felad', head, 0)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is the implementation of a contact list, the contact list is made by two inputs ('feli' and 'fela') the contact list uses trie to find substring and return how many contacts satisfy my search.