-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
MNG-19 Create rankingService.js (#33)
* 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
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |