My array of strings always changes, for example:
["consumables", "spells", "spells", "consumables", "spells", "consumables", "spells", "characters", "characters", "consumables"]
I iterate through this array and based on the index, I execute different .subscribe
functions and add data to a new array.
for (var i = 0; i < arrayOfItems.length; i++) {
switch (arrayOfItems[i]) {
case 'spells':
this.spellsSubscribeSet = true;
this.spellsSubscribe = this.spells.subscribe(data => {
const itemId = this.getRandom(data.length - 1);
this.rewardPack.push(data[itemId]);
});
break;
case 'characters':
this.charactersSubscribeSet = true;
this.charactersSubscribe = this.characters.subscribe(data => {
const itemId = this.getRandom(data.length - 1);
this.rewardPack.push(data[itemId]);
});
break;
case 'consumables':
this.consumablesSubscribeSet = true;
this.consumablesSubscribe = this.consumables.subscribe(data => {
const itemId = this.getRandom(data.length - 1);
this.rewardPack.push(data[itemId]);
});
break;
default:
return null;
}
}
The function .getRandom is just a simple method that generates a random number.
getRandom(x) {
return Math.floor(Math.random() * x);
}
An interesting thing is that only 'spells' are executed multiple times.
I've heard about .flatMap but I don't think it will help me in this scenario since I'm working with a regular array.
This code snippet works with a Firestore database.