Skip to content

Instantly share code, notes, and snippets.

@mauriciomassaia
Created December 20, 2016 00:00
Show Gist options
  • Save mauriciomassaia/81ad7ef46134fcf2685149f492100982 to your computer and use it in GitHub Desktop.
Save mauriciomassaia/81ad7ef46134fcf2685149f492100982 to your computer and use it in GitHub Desktop.
Map index for normal arrays and pixel arrays (RGB) which runs cols by col in inverted order. top to bottom then bottom to top and so on
function ledStripMap(cols, rows) {
var total = cols * rows;
// var map
var map = new Uint8Array(total);
var index = 0;
var count = 0
for(var i = 0; i < cols; i++) {
for (var j = 0; j < rows; j++) {
if (i % 2 === 0) {
index = j * cols + i;
} else {
index = (rows - j - 1) * cols + i;
}
map[count++] = index;
}
}
return map;
}
function applyMap(arr, map) {
var mappedValues = new Uint8Array(arr.length);
for (var i = 0; i < mappedValues.length; i++) {
mappedValues[i] = arr[map[i]];
}
return mappedValues;
}
function applyMapRGB(arr, map) {
var mappedValues = new Uint8Array(arr.length);
var mapIndex;
for (var i = 0; i < mappedValues.length; i += 3) {
mapIndex = map[Math.floor(i / 3)] * 3;
mappedValues[i] = arr[mapIndex];
mappedValues[i + 1] = arr[mapIndex + 1];
mappedValues[i + 2] = arr[mapIndex + 2];
}
return mappedValues;
}
function printArray(a, num) {
for (var k = 0; k < a.length; k+= num) {
console.log(a.slice(k, k + num).toString());
}
}
var map = ledStripMap(5, 20);
// test with 100 values
var arr = new Uint8Array(100);
arr.forEach(function(item, index) { arr[index] = Math.random() * 10 >> 0; });
console.log('original array');
printArray(arr, 5);
console.log('map');
printArray(map, 20);
var mapped = applyMap(arr, map);
console.log('mapped values');
printArray(mapped, 20)
console.log('\n\n\nRGB\n\n');
var mapRGB = ledStripMap(5, 5);
printArray(mapRGB, 5)
// test with 100 pixel so 3 values per pixel
var arrRGB = new Uint8Array(25 * 3);
//arrRGB.forEach(function(item, index) { arrRGB[index] = index; });
arrRGB.forEach(function(item, index) { arrRGB[index] = Math.random() * 255 >> 0; });
var mappedRGB = applyMapRGB(arrRGB, mapRGB);
printArray(arrRGB, 15);
console.log('\n---\n');
printArray(mappedRGB, 15);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment