Last active
July 19, 2016 02:37
-
-
Save nebez/21e27b46725fa5d6de4b6a69354d7972 to your computer and use it in GitHub Desktop.
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
interface Person { | |
name: string; | |
spent: number; | |
} | |
class Trip { | |
private people: Person[]; | |
constructor() { | |
this.people = []; | |
} | |
public addPerson(person: Person): void { | |
this.people.push(person); | |
} | |
public get totalCost(): number { | |
let total = 0; | |
this.people.forEach(p => total += p.spent); | |
return total; | |
} | |
public sortPeopleBySpent(): void { | |
this.people.sort((a, b) => a.spent - b.spent); | |
} | |
public calculateCosts(): void { | |
this.sortPeopleBySpent(); | |
let accumulator = 0; | |
let averageCost = Math.ceil(this.totalCost / this.people.length); | |
console.log(`Total spent: $${this.totalCost}, average per person: $${averageCost}`); | |
this.people.reduce((personA, personB) => { | |
let delta = averageCost - personA.spent; | |
accumulator += delta; | |
console.log(`${personA.name}:`); | |
console.log(` spent $${personA.spent}`); | |
if (delta >= 0) { | |
console.log(` adds $${delta} to the pool`); | |
} else { | |
console.log(` takes $${delta * -1} from the pool`); | |
} | |
console.log(` sends $${accumulator} to ${personB.name}\n`); | |
return personB; | |
}); | |
} | |
} | |
let trip = new Trip(); | |
trip.addPerson({ name: 'Warren', spent: 50 }); | |
trip.addPerson({ name: 'Yannick', spent: 20 }); | |
trip.addPerson({ name: 'Eric', spent: 220 }); | |
trip.addPerson({ name: 'Jason', spent: 140 }); | |
trip.addPerson({ name: 'Sam', spent: 150 }); | |
trip.addPerson({ name: 'Avi', spent: 110 }); | |
trip.addPerson({ name: 'Fonso', spent: 110 }); | |
trip.addPerson({ name: 'Ryan', spent: 20 }); | |
trip.addPerson({ name: 'Nebez', spent: 30 }); | |
trip.calculateCosts(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment