Brief Context
The task should be simple in theory, but I just can’t figure out how to do it. I have a HashMap
that stores player scores. There are 3 types of scores for each player that have the same structure saved in a stable variable. 2 of these I don’t want to touch while I’d like to empty / reset one of them.
Code being used in production
The structure is the following:
private stable var _allTimePlayerScores : [(Principal, PlayerHistoricalStats)] = [];
private var allTimePlayerScores : HashMap.HashMap<Principal, PlayerHistoricalStats> =
HashMap.fromIter(_allTimePlayerScores.vals(), 0, Principal.equal, Principal.hash);
The types mentioned above:
// historical stats is compressed stats without battle records
public type HistoricalStats = {
wins: Nat;
losses: Nat;
points: Nat;
};
// player historical stats contains all historical stats for a player
public type PlayerHistoricalStats = {
arenaStats: HistoricalStats;
tournamentStats: HistoricalStats;
botStats: HistoricalStats;
};
Pseudo code
My intuition would say, just loop through and set everything to 0. Or replace already existing list array an empty array.
for (userScore in userScores) {
userScore.tournamentStats.wins := 0
userScore.tournamentStats.losses := 0
userScore.tournamentStats.points := 0
}
Updated Code
public shared ({caller}) func resetTournamentScores () : async () {
for ((k, v) in allTimePlayerScores.entries()) {
v.tournamentStats.wins := 0;
};
return;
};
For which I’m getting the error: type error [M0073], expected mutable assignment target
To anyone taking the time to read through and help me think of solutions: THANK YOU!
Solution
public shared ({caller}) func resetTournamentScores () : async () {
allTimePlayerScores := HashMap.map<Principal, PlayerHistoricalStats, PlayerHistoricalStats>(allTimePlayerScores, Principal.equal, Principal.hash, func (k, v) {
Debug.print("[Before]: " # debug_show(v));
let updatedScores : PlayerHistoricalStats = {
arenaStats = v.arenaStats;
tournamentStats = {
wins : Nat = 0;
losses : Nat = 0;
points : Nat = 0};
botStats = v.botStats;
};
Debug.print("[After]: " # debug_show(updatedScores));
return updatedScores;
});
return;
};
I’d like to finish up by thanking everyone in the comment section! All of these answers were incredibly helpful!