Here is my code :
class ArrayND {
/**
* @param {Array<number>} ranks
*/
constructor (ranks) {
this.coords = {}
this._ranks = ranks
}
/**
* @param {number|string} defaultValue
*/
init (defaultValue) {
// How to init this.coords with defaultValue given this._ranks ?
}
}
What i want to achieve :
const myArrayND = new ArrayND([3, 2])
myArrayND.init(5)
/*
myArrayND.coords should be :
{
0,0: 5,
0,1: 5,
1,0: 5,
1,1: 5,
2,0: 5,
2,1: 5
}
*/
myArrayND.coords[[2, 1]] // returns 5
My question is : How to implement the init() function, when the ArrayND can be built with any ranks ?
example :
const firstArray = new ArrayND([])
firstArray.init(5)
// firstArray.coords contains {}
const secondArray = new ArrayND([5])
secondArray.init('aze')
/* secondArray.coords contains {
0: 'aze',
1: 'aze',
2: 'aze',
3: 'aze',
4: 'aze',
} */
const thirdArray = new ArrayND([2, 3])
thirdArray.init(2)
/* thirdArray.coords contains {
0,0: 2,
0,1: 2,
0,2: 2,
1,0: 2,
1,1: 2,
1,2: 2,
} */
const anotherExample = new ArrayND([1, 2, 3])
anotherExample.init(1)
/* anotherExample.coords contains {
0,0,0: 1,
0,0,1: 1,
0,0,2: 1,
0,1,0: 1,
0,1,1: 1,
0,1,2: 1,
} */
...
I don't want myObject.coords to contain a multi-dimensional Array because I had other issues to access and set values in a multi-dimensional Array : see JS multidimentional array modify value. It works pretty well, but the ugly switch case is very repelling.
Instead of having
multiDimArray = [
[
[1],
[2],
[3]
],
[
[4],
[5],
[6]
]
]
multiDimArray[0][1][2] // returns 6
Problem is access :
function setValue(indexArray, value) {
switch (indexArray.length) {
case 0:
multiDimArray = value
case 1:
multiDimArray[indexArray[0]] = value
case 2:
multiDimArray[indexArray[0]][indexArray[1]] = value
case 3:
multiDimArray[indexArray[0]][indexArray[1]][indexArrat[2]] =value
...
// Very ugly and isn't truly dynamic
}
}
I want
multiDimArray = {
0,0,0: 1,
0,0,1: 2,
0,0,2: 3,
0,1,0: 4,
0,1,1: 5,
0,1,2: 6,
}
multiDimArray[[0, 1, 2]] // returns 6
That way i can access and set the values dynamically with a function like that : (which was done with an ugly switch case in the case of the Array of Arrays)
function setValue(indexArray, value) {
multiDimArray[indexArray] = value
// much better than before.
}
So i know the name 'ArrayND' can be a bit misleading, but it's not actually an Array, it's a flat object containing the coordinates of the n-dimensional Array.