Tengo dos matrices con la misma longitud. Quiero obtener un elemento de una matriz y continuar agregando su valor (+1) a los demás elementos hasta que el valor sea 0.
Aquí está mi código:
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 ] }Entonces lo que hace es eso;
toma el índice 3 de Array a que es 8 --> a[3] se convirtió en 0
continúe agregando (+1) a sí mismo y a otros elementos de ambas matrices hasta que termine a[3].
Pero aquí está el desafío, quiero pasar por el último elemento de otra matriz (podría ser una matriz a o b ) y nunca agregar +1. Así que mi respuesta debería ser:
answer: { a: [ 1, 1, 0, 1, 1 ], b: [ 1, 1, 1, 1, 0 ] } --> last element of b not changed! const update = (source, target_param, index_param) => { const keys = Object.keys(source) let target = target_param let index = index_param let value = source[target][index] source[target][index] = 0 while (value--) { source[target][index++]++ if (index === source[target].length || target !== target_param && index === source[target].length - 1) { 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)) El cambio más importante es la condición (index === source[target].length || target !== target_param && index === source[target].length - 1) y no mutar los parámetros de la función.
Recomiendo encarecidamente nunca mutar los parámetros de la función.