Lately i have encountered a weird issue. I know there was in C++ a way to send variables as a parameter to a function and have them changed by the called function without having to return it.
Well in JS i knew that would not be possible unless the variable its global. However it does. In some tests I have made this should not be a thing, but with my code in particular this happens.
const setState = (boatShore, boat, state) => {
// this shit should not perform a transition
console.log(JSON.stringify(state))
var valid = validateTransition(boatShore, boat, state)
console.log(JSON.stringify(state)) // the state here is different from the state at line 3.
console.log('\n');
boat = [];
boatShore = boatShore === 0 ? 1 : 0;
return { boatShore, boat, state, valid };
}
// this indeed changes the state in its runtime but it should not affect the caller
function validateTransition(boatShore, boat, state) {
if (boat.length > 2 || boat.length < 1) { return false }
for (let individual of boat) {
if (boatShore !== state[individual.pairIndex][individual.index]) return false;
}
state = transitionState(boat,state)
for (let pair of state) {
if (pair[0] !== pair[1]) {
for (let pairCheck of state) {
if (pairCheck[0] === pair[1]) {
return false;
}
}
}
}
return true;
}
function transitionState(boat,state) {
for (let individual of boat) {
if (state[individual.pairIndex][individual.index] === 0) {
state[individual.pairIndex][individual.index] = 1;
} else {
state[individual.pairIndex][individual.index] = 0;
}
}
return state;
}
problem(4);
function problem(n){
var state = []; //[[0,0], [0,0], [0,0], [0,0]]
var boat = []; //[{ pairIndex: 0, index: 0 },{ pairIndex: 0, index:1 }]
var boatShore = 0;
for (var i = 0; i < n; i++) {
state.push([0, 0]);
}
setState(boatShore, [{ pairIndex: 0, index: 0 },{ pairIndex: 0, index:1 }], state)
}
Here I have a function that should be able to change the "state" variable. For validation i made a separate function that troughout its checks has to check the modified state also. Inside the setState i ran only the function to validate the transition and i did not perform any actual changes to the state. Yet the value of state at line 3 is different compared to the state at line 5, so I must say I am quite confused.
Is there any way to prevent this ? Also why is this happening ?