I have a typescript function which traverse an array of objects, and summary them. It was working if I implicit gives the value a number, however if it comes from input it converts the value to string.
const mmrChanges = matches.reduce<IHistory[]>(
(previous: IHistory[], match: IMatch, index: number) => {
const mmrChange = (match.party_size > 1 ? 20 : 30) * isWon(match); // party game 20 mmr, solo game 30
const prevMmr = previous[previous.length - 1].value;
return [
...previous,
{
index: index,
value: prevMmr mmrChange,
time: new Date(match.start_time * 1000).toISOString().split("T")[0],
},
];
},
[{ index: 0, value: currentMmr, time: "" }]
);
console.log(mmrChanges);
value type is : (property) IHistory.value: number and the current mmr is: const currentMmr: number
However when I start to accumulate the value numbers it starts to concatenate values as strings. currentValue = 400
the next iterate it becomes:
{
"index": 0,
"value": "40030",
"time": "2022-01-25"
}
I tried to force it to number explicitly inside the reduce function with "as number" Also I tried the parseInt() function, but then typescript throws error I cant transform number to int.
What am I missing here? If I change the currentMmr to 0 it is working as intended.
CodePudding user response:
This solution below seem to have achieved the desired results:
const mmrChanges = matches.reduce<IHistory[]>(
(previous: IHistory[], match: IMatch, index: number) => {
const mmrChange = (match.party_size > 1 ? 20 : 30) * isWon(match); // party game 20 mmr, solo game 30
const prevMmr = previous[previous.length - 1].value;
return [
...previous,
{
index: index,
value: prevMmr mmrChange,
time: new Date(match.start_time * 1000).toISOString().split("T")[0],
},
];
},
[{ index: 0, value: parseInt(currentMmr.toString()) || 0, time: "" }]
);
console.log(mmrChanges);
What changed?
The .reduce aggregator was set to [{ index: 0, value: parseInt(currentMmr.toString()) || 0, time: "" }]
Why?
In the question, currentMmr could be any value. In order to ensure that it is always an int, the value prop is set as parseInt(currentMmr.toString()). The .toString() ensures that in case currentMmr is an integer, it is still treated as a string. And, the parseInt transforms the string into an int.
Note: This solution caters to this particular question. It may not work AS IS in other contexts and may need to be customized.
