This repository has been archived by the owner on May 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeaderboardManager.ts
74 lines (63 loc) · 1.8 KB
/
LeaderboardManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
interface StorageAdapter {
save(key: string, data: any): void;
load(key: string): any;
}
class LocalStorageAdapter implements StorageAdapter {
save(key: string, data: any): void {
localStorage.setItem(key, JSON.stringify(data));
}
load(key: string): any {
const data = localStorage.getItem(key);
if (data) {
return JSON.parse(data);
}
return null;
}
}
class Score {
constructor(public name: string, public value: number) {}
}
class LeaderboardManager {
private static LEADERBOARD_STORAGE_KEY = "leaderboard";
private storageAdapter: StorageAdapter;
private scores: Score[];
constructor(storageAdapter: StorageAdapter = new LocalStorageAdapter()) {
this.storageAdapter = storageAdapter;
this.scores = this.loadScores();
}
private loadScores(): Score[] {
const scoresData = this.storageAdapter.load(
LeaderboardManager.LEADERBOARD_STORAGE_KEY
);
if (!scoresData || !Array.isArray(scoresData)) {
return [];
}
return scoresData
.map((scoreData) => {
if (
typeof scoreData.name === "string" &&
typeof scoreData.value === "number"
) {
return new Score(scoreData.name, scoreData.value);
}
return null;
})
.filter((score) => score !== null) as Score[];
}
private saveScores(): void {
this.storageAdapter.save(
LeaderboardManager.LEADERBOARD_STORAGE_KEY,
this.scores
);
}
addScore(name: string, value: number): void {
this.scores.push(new Score(name, value));
this.scores.sort((a, b) => b.value - a.value);
this.scores = this.scores.slice(0, 10); // Keep only top 10 scores
this.saveScores();
}
viewTopScores(): Score[] {
return this.scores.slice(0, 10); // Return top 10 scores
}
}
export default LeaderboardManager;