Created
September 2, 2016 18:22
-
-
Save neight-allen/ebb19d7c802da5697f71770a604a33f7 to your computer and use it in GitHub Desktop.
Huffman decoder solutions
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
//Using Loops | |
Encoder.prototype.decode = function(bitstring) { | |
var bits = bitstring.split(''); | |
var message = ""; | |
while(bits.length) { | |
var currentNode = this.root; | |
while(currentNode.constructor.name == 'Node') { | |
currentNode = (bits.shift() === '0') ? currentNode.left : currentNode.right; | |
} | |
message += currentNode.character; | |
} | |
return message; | |
}; | |
// Using recursion | |
// (For entertainment purposes only. This is not a good idea. You'll exceed the stack limit if your message is too long) | |
Encoder.prototype.decode = function(bitstring) { | |
return this.root.message(bitstring, "", this.root); | |
} | |
Node.prototype.message = function(bitstring, partialMessage = "", rootNode) { | |
bits = bitstring.split(""); | |
bit = bits.shift(); | |
nextNode = bit === '0' ? this.left : this.right; | |
return nextNode.message(bits.join(''), partialMessage, rootNode); | |
} | |
Leaf.prototype.message = function(bitstring, partialMessage, rootNode) { | |
if(bitstring.length) { | |
return rootNode.message(bits.join(''), partialMessage + this.character, rootNode); | |
} | |
else { | |
return partialMessage + this.character; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment