Skip to content

Instantly share code, notes, and snippets.

@usefulthink
Created April 19, 2011 18:30
Show Gist options
  • Save usefulthink/929186 to your computer and use it in GitHub Desktop.
Save usefulthink/929186 to your computer and use it in GitHub Desktop.
Simple implementation of a runlength-encoding algorithm
function encodeFrame(frame, idx) {
// RLE: MSB indicates a run-length (2-127) for the subsequent character
return frame.replace(/(.)\1{2,127}/g, function(s) {
return String.fromCharCode(128 + s.length) + s[0];
});
}
var decodeCache = {};
function decodeFrame(frame) {
return frame.replace(/[\u0080-\u00FF]./g, function replaceCallback(s) {
var c=s[1],
buf=decodeCache[c] || c,
n=s.charCodeAt(0)-128;
while(buf.length <= n) { buf=buf+buf; }
decodeCache[c]=buf;
return buf.slice(0,n);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment