I have two arrays with same length. I want to get an element from one array and continue adding its value (+1) to each other elements until value is 0.
Here is my code:
const update = (source, target, index) => {
const keys = Object.keys(source)
let value = source[target][index]
source[target][index] = 0
while (value--) {
source[target][index++]++
if (index === source[target].length) {
index = 0
target = keys[(keys.indexOf(target) + 1) % keys.length]
}
}
return source
}
console.log(update({a: [0, 0, 0, 8, 0], b: [0, 0, 0, 0, 0]}, 'a', 3))
answer: { a: [ 1, 0, 0, 1, 1 ], b: [ 1, 1, 1, 1, 1 ] }
So what it does is that;
it takes index 3 of Array a which is 8 --> a[3] became 0
continue adding (+1) to itself and other elements of both arrays until a[3] is over.
But here is the challenge, I want to pass by the last element of other array(could be array a or b) and never add +1. So my answer should be:
answer: { a: [ 1, 1, 0, 1, 1 ], b: [ 1, 1, 1, 1, 0 ] } --> last element of b not changed!
update({a: [0, 0, 0, 8, 0], b: [13, 0, 0, 0, 0]}, 'a', 6)take 13?