Created
February 16, 2019 15:31
-
-
Save hexxone/1db4c41745184193b7f946f9fc898b21 to your computer and use it in GitHub Desktop.
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 for "compressing" array data into a shorter array whilst maintaining | |
// the same cross-total value and relativity of values to each other | |
function compressArrayData (arr, toLen) { | |
if (!Array.isArray(arr) || isNaN(toLen) || arr.length < toLen) throw "ArgumentError"; | |
// 1 new data field is equals to this many source fields | |
var sizeRatio = arr.length / toLen; | |
// result storage | |
var results = []; | |
var resIndx = 0; | |
// rest from previous source iteration | |
var rest = 0; | |
// ratio after previous source iteration | |
var lastRatio = sizeRatio; | |
// value carry over | |
var lastVal = 0; | |
for (var i = 0; i < arr.length; i++) { | |
// get rest local and reset it | |
var r = rest; | |
rest = 0; | |
// current value | |
var v = arr[i]; | |
// check if the current value needs to be splitted | |
if (lastRatio < 1) { | |
var c = v * lastRatio; | |
rest = v - c; | |
v = c; | |
} | |
// decrement next source ratio for each iteration | |
lastRatio -= 1; | |
// store the current value | |
lastVal += v + r; | |
// ratio reached => insert value & add next ratio | |
if (lastRatio <= 0) { | |
results[resIndx++] = lastVal; | |
lastVal = 0; | |
lastRatio += sizeRatio; | |
} | |
} | |
return results; | |
} | |
// e.g. this | |
var test = [ 1, 0.5, 0.2, 0.5, 1 ]; //sum 3.2 | |
// becomes this | |
// [ 1.125, 0.475, 0.475, 1.125 ] sum 3.2 | |
var compressd = compressArrayData(test, 4); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment