From bec4b55cfd12647b54b52659af1c52c43ac754c8 Mon Sep 17 00:00:00 2001 From: Tim Glasgow Date: Tue, 9 Aug 2022 07:27:21 -0500 Subject: [PATCH] Score caching --- squarenotsquare/src/realm/DbAPI.js | 4 ++- squarenotsquare/src/realm/repos/ScoreRepo.js | 32 ++++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/squarenotsquare/src/realm/DbAPI.js b/squarenotsquare/src/realm/DbAPI.js index 5e14479..cf78b87 100644 --- a/squarenotsquare/src/realm/DbAPI.js +++ b/squarenotsquare/src/realm/DbAPI.js @@ -31,7 +31,7 @@ class DatabaseAPI { } getHighScores() { - return this.scoreRepo.getHighScores(); + return this.scoreRepo.getCachedScores(); } async initDB() { @@ -39,6 +39,8 @@ class DatabaseAPI { this.systemRepo = repos.systemRepo; this.scoreRepo = repos.scoreRepo; this.userRepo = repos.userRepo; + + this.scoreRepo.loadCache(); } } diff --git a/squarenotsquare/src/realm/repos/ScoreRepo.js b/squarenotsquare/src/realm/repos/ScoreRepo.js index 5050c80..5063065 100644 --- a/squarenotsquare/src/realm/repos/ScoreRepo.js +++ b/squarenotsquare/src/realm/repos/ScoreRepo.js @@ -7,11 +7,31 @@ export default class ScoreRepo { constructor(db) { this.realmDB = db; + this.scoreCache = []; + } + + updateScoreCache = (newScore) => { + this.scoreCache.push(newScore); + this.scoreCache.sort((a, b) => { + a.value < b.value + }); + + if (this.scoreCache.length > 99) { + this.scoreCache = this.scoreCache.slice(99, this.scoreCache.length - 1); + } } createScore = (user, score) => { let scoreID = uuidv4(); + let newScore = { + id: scoreID, + user: user, + value: score + }; + + this.updateScoreCache(newScore); + this.realmDB.write(() => { this.realmDB.create( ScoreEntity.name, @@ -23,7 +43,7 @@ export default class ScoreRepo { true, ); }); - }; + } getHighScores = () => { let score = this.realmDB.objects(ScoreEntity.name).sorted('value', true); @@ -36,5 +56,13 @@ export default class ScoreRepo { highScores.push({user: row.user, value: row.value}); }); return highScores; - }; + } + + loadCache = () => { + this.scoreCache = this.getHighScores(); + } + + getCachedScores = () => { + return this.scoreCache; + } } \ No newline at end of file