Reputation: 73
I am new to JS and programming in general. I am writing an expenses calculator for people who pay for each other. The calculator should allow a person to pay for the whole group or just for part of the group or one person. My issue is that i don't know how to store data for each pair of people. Let's say a groups consists of 5 people. Bob payed for Alice $10. Alice payed $50 for Bob, John and herself and John payed $35 for whole group.
What is a better way to store such calculations?
I was thinking to use object but it doesn't seem to suit in this situation
I need a way to store debt for each pair of people in the group so that i can easily modify this information.
Upvotes: 0
Views: 50
Reputation: 138247
I would just keep an array of transactions:
const all = Symbol();
const transactions = [
{ from: "Alice", to: "Bob", amount: 500 },
{ from: "Bob", to: all, amount: 1000 }
];
That way, you can easily add new transactions, e.g.
transactions.push({ from: "Bob", to: "Alice", amount: 500 });
To then get the current balance between two people, you can go over the transactions and sum them up:
let balance = 0; // from Alice to Bob
for(const { from, to, amount } of transactions) {
if(from === "Alice" && (to === "Bob" || to === all))
balance += amount;
if(from === "Bob" && (to === "Alice" || to === all))
balance -= amount;
}
Upvotes: 1
Reputation: 1286
I would use object (if I don't need to save all the transactions):
Assuming it's a group of 3
const Bob = {
friends: [
{Alice: 10},
],
};
const Alice = {
friends: [
{Bob: 50/3},
{John: 50/3},
],
};
const John = {
friends: [
{Bob: 35/3},
{Alice: 35/3},
],
};
const groupOfFriends = [Bob, Alice, John];
I think from this data structure you can guess who ows who something.
Upvotes: 1