Spaces:
Running
Running
File size: 1,339 Bytes
d83f37d 51cbd57 d83f37d ca26788 d83f37d 51cbd57 d83f37d ca26788 d83f37d 51cbd57 d83f37d | 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 | const DB_KEY = 'vantage_local_database';
const DEFAULT_DATA = {
session: {
questionsAnswered: 0,
correctAnswers: 0,
categoryTotals: {},
},
quizHistory: [],
leaderboard: null,
};
export class LocalDatabase {
static read() {
if (typeof localStorage === 'undefined') {
return { ...DEFAULT_DATA };
}
try {
const raw = localStorage.getItem(DB_KEY);
return raw ? { ...DEFAULT_DATA, ...JSON.parse(raw) } : { ...DEFAULT_DATA };
} catch (error) {
console.warn('Local database read failed; using defaults.', error);
return { ...DEFAULT_DATA };
}
}
static write(patch) {
const next = { ...this.read(), ...patch };
if (typeof localStorage === 'undefined') {
return next;
}
try {
localStorage.setItem(DB_KEY, JSON.stringify(next));
} catch (error) {
console.warn('Local database write failed.', error);
}
return next;
}
static patch(patch) {
return this.write(patch);
}
static saveSession(session) {
return this.write({ session });
}
static saveLeaderboard(leaderboard) {
return this.write({ leaderboard });
}
static addQuizResult(result) {
const data = this.read();
const quizHistory = [result, ...(data.quizHistory || [])].slice(0, 50);
return this.write({ quizHistory });
}
}
|