Sorting: Comparator

  • + 0 comments

    my JS solution - with class

    function processData(input) {
      //Enter your code here
    
      const scores = [];
    
      const inputAr = input.split('\n');
      inputAr.shift();
    
      for (let score of inputAr) {
        scores.push(new Score(score.split(' ')));
      }
    
      scores.sort((a, b) => a.compare(b));
    
      const ranking = scores.map((score) => score.toString());
    
      console.log(ranking.join('\n'));
    }
    
    class Score {
      player = '';
      score = 0;
    
      constructor([player, score] = playerScore) {
        this.player = player;
        this.score = +score;
      }
    
      compare(playerB) {
        return this.score < playerB.score
          ? 0
          : this.score === playerB.score
          ? this.player.localeCompare(playerB.player)
          : -1;
      }
    
      toString() {
        return this.player + ' ' + this.score;
      }
    }