method to create closure. Let's say I have a method to apply different colors to the object. and while mapping the array I have a lot of objects, so their indexes (in map operator) could be uncountable. I have 3 colors and I want to attach a property BG(background color) to them. Like 1st element has 1-st color, 2-nd = 2nd,. third = third, fourth = 1-st color, fifth = 2nd color.
Let's say I have indexes in my method 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
}
I need to transform my indexes to the method to return index 0, 1, 2, and start again from 0,1,2 with saving globally current index
need to create map with key - as last index, and value as next index
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())
CSS SOLUTION
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>