Skip to content

Instantly share code, notes, and snippets.

@DmitryOlkhovoi
Created December 27, 2017 15:17
Show Gist options
  • Save DmitryOlkhovoi/a23b6419e1af2abef47f0f1ffb7c26be to your computer and use it in GitHub Desktop.
Save DmitryOlkhovoi/a23b6419e1af2abef47f0f1ffb7c26be to your computer and use it in GitHub Desktop.
Tries: Contacts solution
class Node {
constructor(word, index = 0) {
this.count = 0
this.children = new Map()
if (word) { // Could be undefined
this.symbol = word[index]
this.completeWord = ((word.length - 1) === index)
if (!this.completeWord) {
this.insert(word, index + 1)
} else {
this.count += 1
}
}
}
insert(word, index = 0) {
this.count += 1
if (word.length === index) {
return false
}
const symbol = word[index]
if (this.children.has(symbol)) {
this.children.get(symbol).insert(word, index + 1)
} else {
this.children.set(
symbol,
new Node(word, index)
)
}
}
getNode(word, index = 0) {
const symbol = word[index]
const nextIndex = index + 1
if (this.children.has(symbol)) {
return this.children.get(symbol).getNode(word, nextIndex)
} else if (word.length === index) {
return this
} else {
return null
}
}
getCount() {
return this.count
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment