You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.2 KiB
58 lines
1.2 KiB
import {ScoreEntity} from '../entities/Score';
|
|
import 'react-native-get-random-values';
|
|
import { v4 as uuidv4 } from 'uuid';
|
|
|
|
export default class ScoreRepo {
|
|
realmDB = null;
|
|
|
|
constructor(db) {
|
|
this.realmDB = db;
|
|
this.scoreCache = [];
|
|
}
|
|
|
|
updateScoreCache = (newScore) => {
|
|
this.scoreCache.push(newScore);
|
|
this.scoreCache.sort((a, b) => b.value - a.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, newScore, true);
|
|
});
|
|
}
|
|
|
|
getHighScores = () => {
|
|
let score = this.realmDB.objects(ScoreEntity.name).sorted('value', true);
|
|
let highScores = [];
|
|
let i = 0;
|
|
score.forEach((row) => {
|
|
if (i > 99){
|
|
return highScores;
|
|
}
|
|
highScores.push({user: row.user, value: row.value});
|
|
});
|
|
return highScores;
|
|
}
|
|
|
|
loadCache = () => {
|
|
this.scoreCache = this.getHighScores();
|
|
}
|
|
|
|
getCachedScores = () => {
|
|
return this.scoreCache;
|
|
}
|
|
}
|