Skip to content

Instantly share code, notes, and snippets.

@ZeeCoder
Last active January 15, 2022 18: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 ZeeCoder/326c0378d1f7994cb3d48e797ae91e23 to your computer and use it in GitHub Desktop.
Save ZeeCoder/326c0378d1f7994cb3d48e797ae91e23 to your computer and use it in GitHub Desktop.
fn buildPathString(node) {
var path = ''
currentNode = node
while (currentNode.parent) {
if (currentNode.parent.left === currentNode) {
// the current node was to the left of its parent, meaning a "."
path = '.' + path
} else {
// the current node was to the right of its parent, meaning a "-"
path = '-' + path
}
// Assuming that "rootNode.parent" would be null,
// which would stop this while loop
currentNode = currentNode.parent
}
return path
}
fn considerNode(string letter, Node node) {
if (node.value === letter) {
// bingo, found our letter, so the path leading to the current node is what we're looking for.
return buildPathString(node)
}
// The current node is not the letter we're looking for.
// Let's look in the left first ("dot" path)
if (node.left) {
// explore the node if it's available
var response = considerNode(letter, node.left)
if (response) {
// Got a match
return response
}
}
// Looking in the right node ("dash" path)
if (node.right) {
// explore the node if it's available
var response = considerNode(letter, node.right)
if (response) {
// Got a match
return response
}
}
// could not find our letter in either the left- or right node.
return null
}
fn encode_letter(Tree tree, string letter) {
var path = considerNode(letter, tree.rootNode)
if (path) {
// The letter was found. The response is a string representing the path, so something like: "--."
return path
} else {
throw new Error('could not find the given letter')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment