fork download
  1. class Klasemen {
  2. constructor(klub) {
  3. this.poin = new Map();
  4. for (const nama of klub) {
  5. this.poin.set(nama, 0);
  6. }
  7. }
  8.  
  9. catatPermainan(klubKandang, klubTandang, skor) {
  10. const [skorKandang, skorTandang] = skor.split(':').map(Number);
  11.  
  12. if (skorKandang > skorTandang) {
  13. this._tambahPoin(klubKandang, 3);
  14. } else if (skorKandang < skorTandang) {
  15. this._tambahPoin(klubTandang, 3);
  16. } else {
  17. this._tambahPoin(klubKandang, 1);
  18. this._tambahPoin(klubTandang, 1);
  19. }
  20. }
  21.  
  22. _tambahPoin(klub, jumlah) {
  23. if (!this.poin.has(klub)) {
  24. this.poin.set(klub, 0);
  25. }
  26. this.poin.set(klub, this.poin.get(klub) + jumlah);
  27. }
  28.  
  29. cetakKlasemen() {
  30. const hasil = {};
  31. [...this.poin.entries()]
  32. .sort((a, b) => b[1] - a[1])
  33. .forEach(([nama, poin]) => {
  34. hasil[nama] = poin;
  35. });
  36. return hasil;
  37. }
  38.  
  39. ambilPeringkat(nomorPeringkat) {
  40. const klasemen = Object.entries(this.cetakKlasemen());
  41. const index = nomorPeringkat - 1;
  42. if (index < 0 || index >= klasemen.length) {
  43. return null;
  44. }
  45. return klasemen[index][0];
  46. }
  47. }
  48.  
  49. const klasemen = new Klasemen(['Liverpool', 'Chelsea', 'Arsenal']);
  50.  
  51. klasemen.catatPermainan('Arsenal', 'Liverpool', '2:1');
  52. klasemen.catatPermainan('Arsenal', 'Chelsea', '1:1');
  53. klasemen.catatPermainan('Chelsea', 'Arsenal', '0:3');
  54. klasemen.catatPermainan('Chelsea', 'Liverpool', '3:2');
  55. klasemen.catatPermainan('Liverpool', 'Arsenal', '2:2');
  56. klasemen.catatPermainan('Liverpool', 'Chelsea', '0:0');
  57.  
  58. console.log(JSON.stringify(klasemen.cetakKlasemen()));
  59.  
Success #stdin #stdout 0.03s 17548KB
stdin
Standard input is empty
stdout
{"Arsenal":8,"Chelsea":5,"Liverpool":2}