Why is my Javascript view on a buffer all zeroes? - javascript

I create a buffer and then a Uint8Array on it, but the array does not have any values. I would expect it to have the values of the buffer. This is an easily reproducible example:
var buf = new ArrayBuffer(32);
for (var index = 0; index < 32; index++) buf[index] = index;
console.log(buf);
var arr = new Uint8Array(buf);
console.log(arr);
The thing I tried in reality is a date format converter like this:
//Buffers and views
function convertDateTimeToFormat(date, initialFormat, endFormat) {
var buf = new ArrayBuffer(14);
var result = new Uint8Array(buf);
console.log(date);
var initialPositions = {};
var endPositions = {};
var sizeSoFar = 0;
for (var c of initialFormat) {
if (c === 'y') {
initialPositions.y = new Uint32Array(date, sizeSoFar, 1);
} else {
initialPositions[c] = new Uint8Array(date, sizeSoFar, 2);
}
sizeSoFar += ((c === 'y') ? 4 : 2);
}
sizeSoFar = 0;
for (var c of endFormat) {
if (c === 'y') {
endPositions.y = new Uint32Array(buf, sizeSoFar, 1);
} else {
endPositions[c] = new Uint8Array(buf, sizeSoFar, 2);
}
sizeSoFar += ((c === 'y') ? 4 : 2);
}
for (var key in initialPositions) {
var limit = (key === 'y') ? 4 : 2;
for (var index = 0; index < limit; index++) endPositions[c][index] = initialPositions[c][index];
}
return result;
}
//2019-03-01 13:03:50
var buf = new ArrayBuffer( 14 );
buf[0] = 2;
buf[1] = 0;
buf[2] = 1;
buf[3] = 9;
buf[4] = 0;
buf[5] = 3;
buf[6] = 0;
buf[7] = 1;
buf[8] = 1;
buf[9] = 3;
buf[10] = 0;
buf[11] = 3
buf[12] = 5;
buf[13] = 0;
console.log(convertDateTimeToFormat(buf, "yMdHms", "yMdHms"));
console.log(convertDateTimeToFormat(buf, "yMdHms", "MdyHms"));
But due to the behavior I described at the start of this question, the results are all zeroes.
This works but it's not elegant, because it expects a date format and if I am to ensure that the input is agnostic to date formats, then the code will become very complicated:
//Buffers and views
var results = {};
var buf = new ArrayBuffer( 4 );
results.uint32 = new Uint32Array(buf);
results.int8 = new Uint8Array(buf);
results.uint8 = new Int8Array(buf);
results.int8[2] = -1;
console.log(results);
results.int8[2] = 0;
results.int8[1] = -1;
console.log(results);
results.int8[1] = 0;
results.int8[0] = -1;
console.log(results);
//Buffers and views
function convertDateTimeToFormat(date, format) {
var buf = new ArrayBuffer(14);
var result = new Uint8Array(buf);
var positions = {
y: 0,
M: 4,
d: 6,
H: 8,
m: 10,
s: 12
};
for (var index = 0; index < 14; index++) {
result[index] = date[positions[format[index]]++];
}
return result.join("");
}
var results = {};
//2019-03-01 13:03:50
var buf = new ArrayBuffer( 14 );
buf[0] = 2;
buf[1] = 0;
buf[2] = 1;
buf[3] = 9;
buf[4] = 0;
buf[5] = 3;
buf[6] = 0;
buf[7] = 1;
buf[8] = 1;
buf[9] = 3;
buf[10] = 0;
buf[11] = 3
buf[12] = 5;
buf[13] = 0;
console.log(convertDateTimeToFormat(buf, "yyyyMMddHHmmss"));
console.log(convertDateTimeToFormat(buf, "MMddyyyyHHmmss"));

An ArrayBuffer is just an object representing a slice of memory. It has a fixed size, that's it. It does not have properties that represent the contents, for that you'll need a typed array as a view on the buffer. Your code is just assigning properties to the buffer which works as it is an object, but it doesn't actually manipulate the byte contents which stay zero.
Don't explicitly instantiate the buffer at all if you don't need it. Just write
var arr = new Uint8Array(32);
for (var index = 0; index < 32; index++) arr[index] = index;
console.log(arr.buffer);
console.log(arr);
In your actual code, it seems you want to use an Uint8Array to store the numbers in individual bytes. And probably you should just pass that array instead of the underlying buffer into the function.
You can create it like this:
const arr = Uint8Array.of(2,0,1,9,0,3,0,1,1,3,0,3,5,0);
// or Uint8Array.from([2,0,1,9,0,3,0,1,1,3,0,3,5,0])
// or new Uint8Array(2,0,1,9,0,3,0,1,1,3,0,3,5,0]);
const buf = arr.buffer;

Related

Why do I get a NaN value and the end of my rubiks cube scramble generator when I remove duplicates?

I am developing a Rubik cube app for fitbit versa and I run into the problem of removing duplicates from arrays as I get a NaN error when combining the arrays once the duplicates have been removed from the end of the list and it only happens when I splice at the end of the array and I cant figure out the reason why this isnt working
function getScramble(number_of_moves, faces, modifiers, scramble_faces, scramble_modifiers, scramble) {
for (var i = 0; i < number_of_moves; i++) {
var sample = faces[Math.floor(Math.random() * faces.length)];
var mod = modifiers[Math.floor(Math.random() * modifiers.length)];
scramble_faces[i] = sample;
scramble_modifiers[i] = mod;
if (scramble_faces[i] == scramble_faces[i - 1]) {
scramble_faces[i] = faces[Math.floor(Math.random() * faces.length)];
}
}
removeDuplicates(scramble_faces, scramble_modifiers)
for (var i = 0; i < number_of_moves - 2; i++) {
scramble[i] = scramble_faces[i] + scramble_modifiers[i]
}
console.log(scramble);
let demotext = document.getElementById("demotext");
demotext.text = scramble;
scramble = [];
scramble_faces = [];
scramble_modifiers = [];
}
function threebythree() {
var faces = ["U", "D", "L", "R", "F", "B"];
var modifiers = ["", "'", "2"];
var scramble_faces = [];
var scramble_modifiers = [];
var scramble = [];
var number_of_moves = 22;
let Title1 = document.getElementById("title");
Title1.text = "3x3"
getScramble(number_of_moves, faces, modifiers, scramble_faces, scramble_modifiers, scramble, Title1)
}
function removeDuplicates(arr, arr2, number_of_moves) {
var t = 0;
var new_arr = arr;
var new_arr2 = arr2;
for (var i = new_arr.length - 1; i >= 0; i--) {
if (new_arr[i] === new_arr[i - 1]) {
new_arr.splice(i, 1);
new_arr2.splice(i, 1);
}
}
arr = new_arr;
arr2 = new_arr2;
new_arr = [];
new_arr2 = [];
new_arr.pop();
new_arr2.pop();
console.log(arr);
console.log(arr2);
}
The lengths of scramble_faces and scramble_modifiers is initially number_of_moves. But after you remove duplicates from them, it can be shorter. But you still use number_of_moves in the limit in the next for loop. So when you try to add the elements that no longer exist you get undefined. undefined + undefined == NaN.
You should use the length of one of the arrays instead:
function getScramble(number_of_moves, faces, modifiers, scramble_faces, scramble_modifiers, scramble) {
for (var i = 0; i < number_of_moves; i++) {
var sample = faces[Math.floor(Math.random() * faces.length)];
var mod = modifiers[Math.floor(Math.random() * modifiers.length)];
scramble_faces[i] = sample;
scramble_modifiers[i] = mod;
if (scramble_faces[i] == scramble_faces[i - 1]) {
scramble_faces[i] = faces[Math.floor(Math.random() * faces.length)];
}
}
removeDuplicates(scramble_faces, scramble_modifiers)
for (var i = 0; i < scramble_faces.length - 2; i++) {
scramble[i] = scramble_faces[i] + scramble_modifiers[i]
}
console.log(scramble);
let demotext = document.getElementById("demotext");
demotext.text = scramble;
scramble = [];
scramble_faces = [];
scramble_modifiers = [];
}

Array Transpose: Error reading property from "Undefined"

Getting an error message for the below code that works to get Values from several cells in my order entry tab named POTemplate and log them in my POHistory tab the serves to compile a list of all order detail entries. As the debugger gets to the bottom of the below code, I get an error message stating: "Cannot Read Property 0.0 from Undefined"
function submit() {
var app = SpreadsheetApp;
var tplSheet = app.getActiveSpreadsheet().getSheetByName("POTemplate");
var tplFRow = 22, tplLRow = tplSheet.getLastRow();
var tplRowsNum = tplLRow - tplFRow + 1;
var tplFCol = 1, tplLCol = 16;
var tplColsNum = tplLCol - tplFCol + 1;
var rangeData = tplSheet.getRange(22, 1, 5, 15).getValues();
var colIndexes = [0, 3, 10, 12, 15];
var fData = filterByIndexes(rangeData, colIndexes);
var target = "POHistory";
var targetSheet = app.getActiveSpreadsheet().getSheetByName(target);
var tgtRow = targetSheet.getLastRow() + 1;
var tgtRowsNum = fData.length - tgtRow + 1;
var tgtCol = 1;
var tgtColsNum = fData[0].length - 1 + 1;
targetSheet.getRange(tgtRow, tgtCol, tgtRowsNum,
tgtColsNum).setValues(fData);
}
function filterByIndexes(twoDArr, indexArr) {
var fData = [];
twoDArr = twoDArr.transpose();
for(var i = 0; i < indexArr.length; i++) {
fData.push(twoDArr[indexArr[i]]);
}
return fData.transpose();
}
Array.prototype.transpose = function() {
var a = this,
w = a.length ? a.length : 0,
h = a[0] instanceof Array ? a[0].length : 0;
if (h === 0 || w === 0) {return [];}
var i, j, t = [];
for (i = 0; i < h; i++) {
t[i] = [];
for (j = 0; j < w; j++) {
t[i][j] = a[j][i];
}
}
return t;
}

Array Processing logic correction

I have an array [1,2,4,5,1,7,8,9,2,3]
and i would like it to generate all subset which sum of values are less than 10
current result [[1,2,4],[5,1],[7],[8],[9],[2,3]]
expected result [[4,5,1],[9,1],[8,2],[3,7],[1,2]]
that is what i did
var a = [1,2,4,5,1,7,8,9,2,3], tempArr = []; tempSum = 0, result = [];
for (var i = 0;i< a.length; i += 1 ) {
tempSum+=a[i];
tempArr.push(a[i]);
if((tempSum+a[i+1])>10) {
result.push(tempArr);
tempSum = 0;
tempArr = [];
} else if (i == a.length-1 && tempArr.length > 0) { // if array is [1,2,3]
result.push(tempArr);
}
}
but it gives me [[1,2,4],[5,1],[7],[8],[9],[2,3]] and it has 6 subset, but i expect to get [[4,5,1],[9,1],[8,2],[3,7],[1,2]] which has 5 subset.
Below logic is in JavaScript :-
var limit = 10;
var arr = [1,2,4,5,1,7,8,9,2,3];
arr.sort();
var ans = new Array ( );
while(arr.length >0){
var ts = arr[arr.length-1];
arr.splice(arr.length-1 , 1);
var ta= new Array ( );
ta.push(ts);
var x = arr.length-1;
while(x>=0){
if(ts + arr[x] <= limit){
ts = ts + arr[x];
ta.push(arr[x]);
arr.splice(x , 1);
}
x= x-1;
}
ans.push(JSON.stringify(ta));
}
alert(ans);
It is Giving Output as required .
[9,1],[8,2],[7,3],[5,4,1],[2]
I have removed duplicates then added maxSum parameter to combine function to generate all subset which have those conditions and then sorted subsets by sum of the values and sliced them.
You could change parameters to fit it for your problem.
var arr = [1,2,4,5,1,7,8,9,2,3]
MAX_SUM = 10,
MIN_SUBSET_LEN = 2,
RESULT_LEN = 5;
//remove duplicates
var uniqeSet = arr.filter(function(value, index){
return this.indexOf(value) == index
},arr);
// a function to get all subset which
// their length are greater than minLength and
// sum of values are little than maxSum
var combine = function(sourceArr, minLength, maxSum) {
var fn = function(n, src, got, all, sum) {
if(sum <= maxSum){
if (n == 0) {
if (got.length > 0) {
all.push({arr:got,sum:sum});
}
return;
}
for (var j = 0; j < src.length; j++) {
var tempSum = sum
fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all, sum + src[j]);
}
}
return;
}
var all = [];
for (var i = minLength; i < sourceArr.length; i++) {
fn(i, sourceArr, [], all, 0);
}
return all;
}
var result = combine(uniqeSet, MIN_SUBSET_LEN, MAX_SUM);
var sortedSliced = result.sort(function(a1, a2){
return a2.sum - a1.sum;
}).slice(0, RESULT_LEN).map(function(m){return m.arr;});
console.log(JSON.stringify(sortedSliced));

Defining a 3D array in JavaScript

I tried to define a 3D array on Google Sheet, but even though I'm using the .slice() method it keeps passing the array by reference.
var temp = [];
for (var a = 0; a<archetypesAll.length; a++) {temp[a] = [0, a].slice();};
var archRank = [];
for (var a = 0; a<21; a++) {archRank[a]= temp.slice();};
archRank[2][1][0] = 'Test';
I want to edit a single element of the matrix but instead the code above just fills every row with the exact same value ('Test'):
3DMatrix[x][1][0] = 'Test'
You can't just copy a multidimensional array by calling slice at the top level, because that will not deep-copy the whole. You have to write your own deepCopy methid, like this:
function allocate(mainDim, ...dims) {
const result = new Array(mainDim);
for (let i = 0; i < result.length; i++) {
result[i] = dims.length > 0 ? allocate(...dims) : 0;
}
return result;
}
function deepCopy(matrix, dims) {
return dims > 1 ? matrix.map(row => deepCopy(row, dims - 1)) : matrix.slice();
}
function test() {
const mx1 = allocate(3,2,2);
mx1[2][1][0] = "Test";
console.log(JSON.stringify(mx1));
const mx2 = deepCopy(mx1, 3);
mx2[2][1][0] = "Copied";
console.log(JSON.stringify(mx1));
console.log(JSON.stringify(mx2));
}
test();
var array = ["Test", "Test"];
var array3d = [[array.slice(0)],[[array.slice(0)]]];
array3d[0][0][0] = "Changed";
console.log(JSON.stringify(array3d)); //[[["Changed","Test"]],[[["Test","Test"]]]]
Try with this instead of slice to get a new array instead of reference:
var temp = [];
for (var a = 0; a < archetypesAll.length; a++) {
temp[a] = JSON.parse(JSON.stringify([0, a]));
}
var archRank = [];
for (var a = 0; a < 21; a++) {
archRank[a]= temp.slice();
}
archRank[2][1][0] = 'Test';

XYZ dimensional array

Why is this code shown array[7][0] is undefined when it should have a value?
var tnotes = [];
var index = 0;
for (var i = 0; i < 14; i++) {
tnotes[i] = [];
}
var tx = 'B4';
var notes=['B5','A5','G5','F5','E5','D5','C5','B4','A4','G4','F4','E4','D4','C4']
var getNotes = notes.indexOf(tx);
if (getNotes != -1) {
tnotes[getNotes][index][] = new Array(20)
tnotes[getNotes][index][0] = tx //B4
tnotes[getNotes][index][2] = '3sec'
index++
}
console.log(tnotes[7][0])
You simply have a syntax error in defining one of your sub-arrays. The following line is incorrect:
tnotes[getNotes][index][] = new Array(20)
You are introducing a third-dimension of your tnotes array without it being defined
It should be:
tnotes[getNotes][index] = [];
Or if you really need the size parameter:
tnotes[getNotes][index] = new Array(20);
After this, tnotes[7][0] should no longer be undefined. Also, please do yourself a favor and make sure you use semi-colons consistently, it's good practice and can save you many-a-headache.
Corrected code:
var tnotes = [];
var index = 0;
for (var i = 0; i < 14; i++) {
tnotes[i] = [];
}
var tx = 'B4';
var notes = ['B5','A5','G5','F5','E5','D5','C5','B4','A4','G4','F4','E4','D4','C4'];
var getNotes = notes.indexOf(tx);
if (getNotes != -1) {
tnotes[getNotes][index] = [];
tnotes[getNotes][index][0] = tx; //B4
tnotes[getNotes][index][2] = '3sec';
index++;
}
console.log(tnotes[7][0]);

Categories