Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save transparenceweb/2fa3324d3b41fdc033c2dab62255c798 to your computer and use it in GitHub Desktop.
Save transparenceweb/2fa3324d3b41fdc033c2dab62255c798 to your computer and use it in GitHub Desktop.
Code challenge from 9th May 2022 email from Cassidoo
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));
@transparenceweb
Copy link
Author

transparenceweb commented May 11, 2022

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 after line 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment