método para crear el cierre. Digamos que tengo un método para aplicar diferentes colores al objeto. y mientras mapeo la matriz, tengo muchos objetos, por lo que sus índices (en el operador de mapa) podrían ser incontables. Tengo 3 colores y quiero adjuntarles una propiedad BG (color de fondo). Como el primer elemento tiene el primer color, el segundo = el segundo. tercero = tercero, cuarto = 1er color, quinto = 2do color.
Digamos que tengo índices en mi método 0, 1, 2, 3, 4, 5...
public sendIndex() { const users = this.users.map((user, index) => { if (!user.property) { this.currentIndex = index; // ? return { ...user, bg: this.transformIndex(index), }; } }); } public transformIndex(i) { // index should be 0,1,2,3,4 ..... endless }Necesito transformar mis índices al método para devolver el índice 0, 1, 2 y comenzar de nuevo desde 0,1,2 guardando el índice global actual
necesita crear un mapa con key : como último índice y value como el siguiente índice
const users = [{id: 1},{id: 2},{id: 3},{id: 4},{id: 5},{id: 6},{id: 7},{id: 8},{id: 9},{id: 10}]; const mapIndex = { 2:0, 1:2, 0:1 }; function transform() { let last = undefined; return users.map(el => { last = last === undefined ? 0 : mapIndex[last] el.bg = last; return el; }) } console.log(transform())SOLUCIÓN CSS
div {height: 20px;margin: 5px;} div:nth-child(3n+1) {background: blue;} div:nth-child(3n+2) {background: red;} div:nth-child(3n+3) {background: green;} <div> 1 blue</div> <div>2 red</div> <div>3 green</div> <div>4 blue</div> <div> 5 red</div> <div> 6 green</div> <div> 7 blue</div> <div> 8 red</div> <div> 9 green</div>