Last active
May 16, 2022 06:45
-
-
Save transparenceweb/2fa3324d3b41fdc033c2dab62255c798 to your computer and use it in GitHub Desktop.
Code challenge from 9th May 2022 email from Cassidoo
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
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 } | |
]; | |
function whoOwes(array) { | |
const meal_count = array.length; | |
let unique_people = new Set(); | |
let culmulative_meal_cost = 0; | |
let paid_per_person = { | |
"Cassidy": 0, | |
"Clara": 0, | |
"Ximena": 0 | |
}; | |
let meal_details = []; | |
for (i = 0; i < meal_count; i += 1) { | |
let meal_cost = array[i].paid; | |
let payer = array[i].name; | |
unique_people.add(payer); | |
paid_per_person[`${payer}`] += meal_cost; | |
culmulative_meal_cost += meal_cost; | |
} | |
meal_details.push(paid_per_person,culmulative_meal_cost,unique_people); | |
const person_total = meal_details[0]; | |
const meals_total = meal_details[1]; | |
const people_count = meal_details[2].size; | |
const fair_amount_per_person = (meals_total / people_count); | |
let overpayer = ""; | |
let differential = {}; | |
for (const [key, value] of Object.entries(person_total)) { | |
if (value < fair_amount_per_person) { | |
differential[`${key}`] = (fair_amount_per_person - value); | |
} else { | |
overpayer = key; | |
} | |
} | |
let underpayers = Object.keys(differential); | |
let underpaid = Object.values(differential); | |
let message = ""; | |
for (i = 0; i < underpayers.length; i++) { | |
message +=`${underpayers[i]} owes ${overpayer} \$${underpaid[i]}. ` | |
} | |
return message; | |
}; | |
console.log(whoOwes(receipts)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not completely happy with this. Feels like I am missing a trick. I’ve had to manually add ‘starter’ values at
line 15–17
which feels like I should be able to set programmatically afterline 23
. Couldn’t get this to work though. Struggling with adding items to objects based on what was, or would be, in the set.Originally write as multiple smaller functions, then collapsed down into one where the only argument passed was receipts.
Good fun and thought-provoking.