-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstats.js
40 lines (40 loc) · 1.2 KB
/
stats.js
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
export default class Stats {
constructor(storage) {
this.storage = storage;
}
validate = (s) => {
if (typeof s !== "object") return false;
const statObjKeys = [
"avgTime",
"points",
"correctAnswers",
"numOfQuestions",
"rating",
"ts",
];
const missingParams = statObjKeys.reduce((acc, key) => {
if (s[key] === undefined) return acc + 1;
return acc;
}, 0);
const hasParams = Object.keys(s);
if (missingParams === 0 && hasParams.length === statObjKeys.length)
return true;
return false;
};
save = (playerId, gameName, result) => {
return new Promise((resolve, reject) => {
if (!this.validate(result)) return resolve(false);
this.storage
.read(playerId)
.then((gamesResults) => {
if (gamesResults === undefined || gamesResults === null || typeof(gamesResults) === "string") gamesResults = {};
if (!gamesResults[gameName]) gamesResults[gameName] = [];
gamesResults[gameName].push(result);
this.storage.write(playerId, gamesResults);
resolve(true);
})
.catch(reject);
});
};
get = (playerId) => this.storage.read(playerId);
};