Created
May 13, 2022 07:33
-
-
Save g-bel/b063fcfda110cb5a1d804b8743e5323f to your computer and use it in GitHub Desktop.
Cassidy Williams - question of the week 2021-05-09
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
const whoOwes = (receipts) => { | |
const people = {}; | |
let total = 0; | |
for (const { name, paid } of receipts) { | |
people[name] = people[name] === undefined ? paid : people[name] + paid; | |
total += paid; | |
} | |
const totalEach = Math.floor(total * 100 / Object.keys(people).length) / 100; // Divide with cents | |
const owesList = []; | |
const owedList = []; | |
const result = []; | |
for (const person of Object.keys(people)) { | |
const tripResult = people[person] - totalEach; | |
if (tripResult > 0) { | |
owedList.push({ name: person, owed: tripResult }); | |
} else if (tripResult < 0) { | |
owesList.push({ name: person, owes: tripResult }); | |
} | |
} | |
for (let { name, owes } of owesList) { | |
while (owes < 0) { | |
const oP = owedList.at(-1); | |
if (Math.abs(owes) >= oP.owed) { | |
result.push(`${name} owes ${oP.name} $${oP.owed}`); | |
owedList.pop(); | |
owes += oP.owed; | |
} else { | |
result.push(`${name} owes ${oP.name} $${Math.abs(owes)}`); | |
owedList.at(-1).owed += owes; | |
owes = 0; | |
} | |
} | |
} | |
return result.join(', '); | |
}; | |
let receipts = [ | |
{ name: 'Ximena', paid: 45 }, | |
{ name: 'Clara', paid: 130 }, | |
{ name: 'Ximena', paid: 100 }, | |
{ name: 'Cassidy', paid: 140 }, | |
{ name: 'Cassidy', paid: 76 }, | |
{ name: 'Clara', paid: 29 }, | |
{ name: 'Ximena', paid: 20 }, | |
]; | |
console.log(whoOwes(receipts)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment