Skip to content

Commit

Permalink
MNG-19 Create rankingService.js (#33)
Browse files Browse the repository at this point in the history
* Create rankingService.js

* MNG-19 Update rankingService.js

some small changes and:
- removed print to html function
- created update from localStorage function
  • Loading branch information
memeraki authored Jan 14, 2021
1 parent b7d8530 commit f9621a6
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/service/rankingService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
export const rankingService = (mode, user) => {
const PokemonApiRanking = checkLocalStorage(); //update from localStorage
let currentMode; //path to scores array for current mode
switch(mode) {
case WHO_IS_THAT_POKEMON:
currentMode = PokemonApiRanking.mode1.scores;
break;
case WHAT_DOES_THIS_POKEMON_LOOK_LIKE:
currentMode = PokemonApiRanking.mode2.scores;
break;
case GUESS_THE_TYPE:
currentMode = PokemonApiRanking.mode3.scores;
break;
default:
throw new Error('Wrong game mode!');
}
currentMode.push(user);
currentMode.sort( (a,b) => {
const scoreCompare = b.score - a.score;
if(scoreCompare != 0) { // compare scores
return scoreCompare;
} else { // scores are the same => compare times
return b.timeInSeconds - a.timeInSeconds;
}
} );
if(currentMode.length > 3) {
currentMode.pop();
}

localStorage.setItem('PokemonApiRanking', JSON.stringify(PokemonApiRanking)); //save in localStorage
}

const checkLocalStorage = () => {
const PokemonApiRanking = JSON.parse(localStorage.getItem('PokemonApiRanking')) || {
mode1: {
name : "Whos that pokemon?",
scores : []
},
mode2: {
name : "What it looks like?",
scores : []
},
mode3: {
name : "Guess the type!",
scores : []
}
}
return PokemonApiRanking;
}

0 comments on commit f9621a6

Please sign in to comment.