Skip to content

Instantly share code, notes, and snippets.

@felipediogo
Created June 28, 2018 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipediogo/2b41687101a51bb3ef655b265a56c5bb to your computer and use it in GitHub Desktop.
Save felipediogo/2b41687101a51bb3ef655b265a56c5bb to your computer and use it in GitHub Desktop.
Implementation of trie (data structure) in JS
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));
@felipediogo
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment