DEV Community

Discussion on: Daily Challenge #121 - Who has the most money?

Collapse
 
erezwanderman profile image
erezwanderman

Javascript:

class Student {
  constructor(name, fives, tens, twenties) {
    this.name = name;
    this.fives = fives;
    this.tens = tens;
    this.twenties = twenties;
  }
}

const mostMoney = (students) => {
  const studentsMoney = (student) => student.fives * 5 + student.tens * 10 + student.twenties * 20;
  if (students.length === 1) {
    return students[0].name;
  }
  if (students.length > 1) {
    const firstStudentMoney = studentsMoney(students[0]);
    const secondStudentMoney = studentsMoney(students[1]);
    if (firstStudentMoney === secondStudentMoney) {
      return 'all';
    }
    let [maxName, maxMoney] = firstStudentMoney > secondStudentMoney ? [students[0].name, firstStudentMoney] : [students[1].name, secondStudentMoney];
    for (let i = 2; i < students.length; i++) {
      const money = studentsMoney(students[i]);
      if (money > maxMoney) {
        [maxName, maxMoney] = [students[i].name, money];
      }
    }
    return maxName;
  }
}

Usage:

const x = [
  new Student('John1', 2, 0, 1),
  new Student('John2', 5, 1, 0),
  new Student('John3', 40, 1, 0),
];
appDiv.innerText = mostMoney(x);