Skip to content

Instantly share code, notes, and snippets.

@earlonrails
Created January 25, 2018 17:57
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 earlonrails/72ca0da3fdf24977a4586ed282031f76 to your computer and use it in GitHub Desktop.
Save earlonrails/72ca0da3fdf24977a4586ed282031f76 to your computer and use it in GitHub Desktop.
Contacts Problem in ES6, people still know what Rolodexs are right?
#!/usr/bin/env node
"use strict"
// hackerrank https://www.hackerrank.com/challenges/ctci-contacts/problem
// add hack
// add hackerrank
// find hac
// find hak
// var alphabet = 'abcdefghijklmnopqrstuvwxyz'
class Rolodex {
constructor(debug) {
this.masterNode = new Node()
this.debug = debug
}
add(str) {
if (this.debug) console.log("starting add: ", str)
var strArr = str.split('')
var node = new Node(strArr.shift())
node = this.masterNode.addChild(node, (strArr.length == 1), this.debug)
while(strArr.length > 0) {
if (this.debug) console.log("while loop adding: ", strArr[0])
var newNode = new Node(strArr.shift(), (strArr.length == 1), this.debug)
node = node.addChild(newNode)
}
if (this.debug) {
console.log("masterNode: ")
console.dir(this.masterNode)
}
}
find(str) {
var count = 0
if (this.debug) console.log("finding: ", str)
var strArr = str.split('')
var node = this.masterNode
while(node && strArr[0]) {
if (this.debug) console.log("getting child: ", strArr[0])
var child = node.getChildNode(strArr.shift())
if (child && strArr.length == 0) {
if (this.debug) console.log("child count: ", node.count)
count = child.count
}
node = child
}
console.log(count)
return count
}
}
class Node {
constructor(letter, last, debug) {
this.children = []
this.letter = letter
this.isLast = last
this.count = 1
this.debug = debug
}
getCharCode(letter) {
return letter.charCodeAt(0) - 97
}
getChildNode(letter) {
if (!letter) return
return this.children[this.getCharCode(letter)]
}
setChildNode(node) {
this.children[this.getCharCode(node.letter)] = node
}
addChild(node) {
if (this.debug) {
console.log("adding child: ", node.letter, "to: ", this.letter)
console.log("current node: ", this.letter, "children: ", this.children)
}
var child = this.getChildNode(node.letter)
if (child) {
child.count += 1
if (this.debug) console.log("child found:", child)
return child
} else {
if (this.debug) console.log("child missing:", node.letter)
this.setChildNode(node)
return node
}
}
}
var r = new Rolodex()
r.add("hack")
r.add("hacker")
r.add("hackist")
r.add("beer")
r.add("bee")
r.add("beet")
r.add("bear")
r.add("beast")
r.add("feet")
r.add("foot")
r.find("hac")
r.find("hak")
r.find("bee")
r.find("bea")
r.find("f")
r.find("zebra")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment