Created
October 4, 2016 18:42
-
-
Save samuelfvlcastro/965ca9b9e4036eafe56c5b1d1405b754 to your computer and use it in GitHub Desktop.
Example of Run-length encoding (RLE) compression in javascript
This file contains 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
var blocks = ["A","A","A","A","A","A","A","A","A","A","A","A","B","B","A","C","C","C","C","D","D","D","D","A","A","E","E","E","A"]; | |
function Encode(input){ | |
var segmentLength = blocks.length; | |
var run = 0, current = '', last = '', encoded = ''; | |
current = last = blocks[0]; | |
for(var i = 1; i <= segmentLength; i++){ | |
if(current !== last){ | |
encoded += run + last; | |
run = 0; | |
last = current; | |
} | |
current = blocks[i]; | |
run++; | |
} | |
encoded += run + last; | |
return encoded; | |
} | |
function Decode(input){ | |
var decoded = []; | |
var result = input.replace(/(\d+\D{1})/g, function (match) { | |
var current = match.slice(-1) | |
var run = match.slice(0, -1); | |
decoded = decoded.concat(Array.apply(null, Array(parseInt(run))).map(String.prototype.valueOf,current)); | |
}); | |
return decoded; | |
} | |
var encoded = Encode(blocks); | |
var decoded = Decode(encoded); | |
var reEncode = Encode(decoded); | |
console.log("Raw: ", blocks) | |
console.log("Encoded: ", encoded); | |
console.log("Decoded: ", decoded); | |
console.log("Reencoded:",reEncode) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The problem is if you pass in something like
XYZ
toEncode
, you get1X1Y1Z
, which is actually longer.