Last active
January 15, 2022 18:57
-
-
Save ZeeCoder/326c0378d1f7994cb3d48e797ae91e23 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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