Seeking guidance on a unique approach to handling array looping in TypeScript. Rather than the usual methods, my query pertains to a specific scenario which I will elaborate on.
The structure of my JSON data is as follows:
{
"forename": "Maria",
"colors": [
{
"name": "blue",
"price": 10
},
{
"name": "yellow",
"price": 12
}
],
"items": [
{
"name": "sword",
"price": 20
}
],
"specialPowers": [
{
"name": "telekinesis",
"price": 34
}
]
},
{
"forename": "Peter",
"colors": [
{
"name": "blue",
"price": 10
}
],
"items": [
{
"name": "hat",
"price": 22
},
{
"name": "hammer",
"price": 27
}
]
}
// additional individuals and data
In this setup, each person can possess arrays such as colors, items, or specialPowers. However, it's also possible for a person to have none of these arrays; for instance, Maria has specialPowers but Peter does not.
I am in need of a function that can determine if a person possesses any of these arrays and calculate the total price of all their possessions. In essence, summing up the prices of everything a person owns.
Currently, I have three separate functions structured similarly:
getTotalOfColors(person) {
let total = 0;
if(person.colors)
for (let color of person.colors) {
total += color.price;
}
return total;
}
getTotalOfItems(person) {
let total = 0;
if(person.items)
for (let item of person.items) {
total += item.price;
}
return total;
}
// SIMILAR FUNCTION FOR SPECIALPOWERS
All these functions follow the same process with slight differences due to iterating over different arrays. Is there a more efficient way to consolidate them into one universal function? I envision a single function that iterates through various arrays within a person object, accumulating prices accordingly.
This unified function might resemble the following:
getTotal(person) {
let total = 0;
for (let possibleArray of possibleArrays){
if(person.possibleArray )
for (let var of person.possibleArray ) {
total += var.price;
}
}
return total;
}
To implement this, I believe I would require an array listing the potential arrays like so: possibleArrays = [colors, items, specialPowers]. How can I establish and utilize this array effectively within my code? Alternatively, are there better solutions to address this issue?