71 lines
2.0 KiB
JavaScript
71 lines
2.0 KiB
JavaScript
import Module from "./Module.js";
|
|
|
|
const MODULE_NAME = "HIGHSCORE";
|
|
const HIGHSCORE_LENGTH = 10;
|
|
|
|
const initialState = {
|
|
highscores: [],
|
|
lastUsername: "",
|
|
lastGameId: null
|
|
};
|
|
|
|
export const module = new Module(MODULE_NAME, initialState);
|
|
|
|
export const [UPDATE_HIGHSCORE, updateHighscore] = module.action("UPDATE_HIGHSCORE");
|
|
export const [SKIP_HIGHSCORE, skipHighscore] = module.action("SKIP_HIGHSCORE", gameId => ({ gameId }));
|
|
export const [REGISTER_HIGHSCORE, registerHighscore] = module.action(
|
|
"REGISTER_HIGHSCORE",
|
|
({ name, score, gameId }) => ({
|
|
name,
|
|
score,
|
|
gameId
|
|
})
|
|
);
|
|
|
|
export const sortHighscores = highscores =>
|
|
highscores.sort((a, b) => {
|
|
if (a.score > b.score) {
|
|
return -1;
|
|
}
|
|
if (a.score < b.score) {
|
|
return 1;
|
|
}
|
|
if (a.gameId < b.gameId) {
|
|
return -1;
|
|
}
|
|
if (a.gameId > b.gameId) {
|
|
return 1;
|
|
}
|
|
return 0;
|
|
});
|
|
|
|
export const updateHighscores = (highscores, { name, score, gameId }) => {
|
|
const newHighscores = [...highscores, { name, score, gameId }];
|
|
return sortHighscores(newHighscores).slice(0, HIGHSCORE_LENGTH);
|
|
};
|
|
|
|
/* === Selectors ================================================================================ */
|
|
|
|
export const hasHighscore = module.selector(
|
|
({ [MODULE_NAME]: { highscores = [] } = { highscores: [] } } = { [MODULE_NAME]: { highscores: [] } }, score) => {
|
|
const currentScores = sortHighscores(highscores || []).slice(0, HIGHSCORE_LENGTH);
|
|
if (currentScores.length < HIGHSCORE_LENGTH) {
|
|
return true;
|
|
}
|
|
return score > (currentScores[currentScores.length - 1] || { score: 0 }).score;
|
|
}
|
|
);
|
|
|
|
/* === Reducers ================================================================================= */
|
|
|
|
module.reducer(REGISTER_HIGHSCORE, (state = {}, { name, score, gameId }) => ({
|
|
...state,
|
|
lastGameId: gameId,
|
|
lastUsername: name,
|
|
highscores: updateHighscores(state.highscores || [], { name, gameId, score })
|
|
}));
|
|
|
|
module.reducer(SKIP_HIGHSCORE, (state = {}, { gameId }) => ({ ...state, lastGameId: gameId }));
|
|
|
|
export default module;
|