Skip to content

Instantly share code, notes, and snippets.

@RyanHirsch
Created February 24, 2019 15:22
Show Gist options
  • Save RyanHirsch/7c525e4233b92dd03d0147bc2409cc50 to your computer and use it in GitHub Desktop.
Save RyanHirsch/7c525e4233b92dd03d0147bc2409cc50 to your computer and use it in GitHub Desktop.
An attempt to implement what is described and illustrated based on the first 2 minutes of https://www.youtube.com/watch?v=vlYZb68kAY0&index=8&list=PLI1t_8YX-Apv-UiRlnZwqqrRT8D1RhriX&t=164s no clue if it is right
const splitAt = (index: number) => (x: string) => [x.slice(0, index), x.slice(index)];
const splitFirst = splitAt(1);
class ContactNode {
contactsCount: number = 0;
data: { [letter:string]: ContactNode } = {}
add(contact: string) {
this.contactsCount++;
const [firstLetter, rest] = splitFirst(contact);
if(!firstLetter) { return }
if(!this.data[firstLetter]) {
this.data[firstLetter] = new ContactNode();
}
this.data[firstLetter].add(rest);
}
findCount(contact: string) {
const [firstLetter, rest] = splitFirst(contact)
if(!firstLetter) {
return this.contactsCount;
}
if(!this.data[firstLetter]) {
return 0;
}
return this.data[firstLetter].findCount(rest);
}
}
const allContacts = new ContactNode();
allContacts.add("sally")
allContacts.add("john");
allContacts.add("jenny");
allContacts.add("jonny")
allContacts.add("jim");
console.log(allContacts.contactsCount);
console.log(allContacts.findCount("j"));
console.log(allContacts.findCount("ji"));
console.log(allContacts.findCount("jim"));
console.log(allContacts.findCount("jo"));
console.log(allContacts.findCount("je"));
console.log(allContacts.findCount("x"));
console.log(allContacts.findCount("jx"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment