Last active
May 5, 2016 22:30
-
-
Save BriSeven/7972a56c0e9d89951ddfa55c85328176 to your computer and use it in GitHub Desktop.
Run Length Encoding and Decoding for JS number arrays, with Delta Encoding and Delta Decoding.
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
function RLEencode(array) { | |
// output an array of values | |
// consisting of alternating "rips" and "runs" | |
// a rip begins with a negative count followed by a | |
// cooresponding number of non-repeating values | |
// | |
// a run begins with a positive count, followed by | |
// the value to be repeated by the count. | |
var newArray=[]; | |
var rip=[]; | |
var lastValue=undefined; | |
var runCount=0; | |
for (var i = 1,lastValue=array[0]; i <= array.length; i++) { | |
if(array[i]!==lastValue){ | |
if(runCount!==0){ | |
newArray.push(runCount+1,lastValue); | |
} else { | |
rip.push(lastValue); | |
} | |
runCount=0; | |
} | |
if(array[i]===lastValue || i===array.length){ | |
if(rip.length !== 0){ | |
if(rip.length){ | |
newArray.push(-rip.length); | |
newArray=newArray.concat(rip); | |
} | |
rip=[]; | |
} | |
runCount++; | |
} | |
lastValue=array[i]; | |
}; | |
return newArray; | |
} | |
function RLEdecode(array) { | |
var newArray=[],isRip,isRun,ripCount,runCount; | |
for (var i = 0; i < array.length; i++) { | |
isRip=array[i]<0; | |
isRun=array[i]>0; | |
if(isRip){ | |
ripCount=Math.abs(array[i]); | |
i+=1; | |
newArray=newArray.concat(array.slice(i,i+ripCount)); | |
// console.log("rip",ripCount,array.slice(i,i+ripCount)); | |
i+=ripCount-1; | |
} | |
if(isRun){ | |
runCount=array[i]; | |
i+=1; | |
for (var j = 0; j < runCount; j++) { | |
newArray.push(array[i]) | |
}; | |
} | |
}; | |
return newArray; | |
} | |
function deltaEncode (array) { | |
var newArray=[]; | |
var lastval=0; | |
var count=0; | |
var i; | |
for(i=0;i<array.length;i++){ | |
newArray[i] = array[i] - lastval; | |
lastval = array[i]; | |
} | |
return newArray; | |
} | |
function deltaDecode (array) { | |
var newArray=[]; | |
var lastval=0; | |
var count=0; | |
var i; | |
for(i=0;i<array.length;i++){ | |
lastval= newArray[i] = array[i] + lastval; | |
} | |
return newArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment