I know its a bit convoluted, but consider this hypothetical:
class test {
points = [[10,15]];
rotate (angle){
let deg = angle *= Math.PI/180; //degrees to radians
this.points.map((point, pointIndex) => point.map((value, axis) => this.points[pointIndex][axis] = axis === 0 ? (this.points[pointIndex][0]*Math.cos(deg)-this.points[pointIndex][1]*Math.sin(deg)):(this.points[pointIndex][1]*Math.cos(deg)+this.points[pointIndex][0]*Math.sin(deg))));
//This essentially maps the current points to their projections after rotating them by some angle
//It performs two different operations respective to the two different values in the nested array
}
}
let foo = new test;
foo.rotate(90);
console.log(foo.points);
Running this will return:
Array [ -15, -14.999999999999998 ]
Which, for arguments sake, is not the intended result.
At first I assumed it had something to do with the use of the "?" operator, but eliminating this and separating the outcomes into their own mapping:
class test {
points = [[10,15]];
rotate (angle){
let deg = angle *= Math.PI/180;
this.points.map((point, pointIndex) => this.points[pointIndex][0]=(this.points[pointIndex][0]*Math.cos(deg)-this.points[pointIndex][1]*Math.sin(deg)));
this.points.map((point, pointIndex) => this.points[pointIndex][1]=(this.points[pointIndex][1]*Math.cos(deg)+this.points[pointIndex][0]*Math.sin(deg)));
}
}
let foo = new test;
foo.rotate(90);
console.log(foo.points);
But this results in the same outcome. However, when running either of line by itself, which, because they are split, affects only the first or second element depending on which is eliminated, the accurate result is returned:
Array [ -15, 15 ] (if the second line is removed) Array [ 10, 10.000000000000002 ] (if the first line is removed)
Both of which return the accurate value of their respective index. ([ -15, 10.000000000000002 ] is correct, taking the first element of the first array and the second of the second.)
For some reason, by running them in succession, something fails.
Thank you in advance.
Edit: The same issue occurs when using forEach().
You shouldn't access the current object inside an transformation.
class test {
points = [[10,15]];
rotate (angle){
let deg = angle * Math.PI/180; //degrees to radians
this.points = this.points.map((point) => {
let newPoint = [0,0];
newPoint[0] = point[0]*Math.cos(deg)-point[1]*Math.sin(deg);
newPoint[1] = point[1]*Math.cos(deg)+point[0]*Math.sin(deg);
return newPoint
})
//This essentially maps the current points to their projections after rotating them by some angle
//It performs two different operations respective to the two different values in the nested array
}
}
let foo = new test;
foo.rotate(90);
console.log(foo.points);