Skip to content

Instantly share code, notes, and snippets.

@samuelfvlcastro
Created October 4, 2016 18:42
Show Gist options
  • Save samuelfvlcastro/965ca9b9e4036eafe56c5b1d1405b754 to your computer and use it in GitHub Desktop.
Save samuelfvlcastro/965ca9b9e4036eafe56c5b1d1405b754 to your computer and use it in GitHub Desktop.
Example of Run-length encoding (RLE) compression in javascript
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)
@SiddharthShyniben
Copy link

The problem is if you pass in something like XYZto Encode, you get 1X1Y1Z, which is actually longer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment