我正在尝试创建一个人们欠对方钱的应用程序。让人说他的朋友购买电影票,每张票的成本是20美元。现在他的每个朋友都欠那个人20美元。
我确实做了一个对象,但我认为这不是正确的方法。我想知道是否有更好的方法可以做到。
例如 person1 to person2:20美元。 person3 to person2:20美元。 person2 to person1:$ 0。 person2 to person3:$ 0。
我已经接近这样了
var person1 = new User(1, "person1", [{"name": "person2", "amount": 0}, {"name": "person3, "amount": 0}]);
var person2 = new User(2, "person2", [{"name": "person1", "amount": 0}, {"name": "person3, "amount": 0}]);
var person3 = new User(3, "person3", [{"name": "person1", "amount": 0}, {"name": "person2", "amount": 0}]);
答案 0 :(得分:0)
我不建议将"交易"对用户本身。分开保存。也许就是这样。
// just an quick example using typescript
class User {
public readonly id: string;
public readonly name: string;
constructor(name?: string) {
this.name = name || 'unknown';
this.id = Math.random(); // just an example;
}
}
class Transaction {
private target: string;
public readonly date: number;
public readonly origin: string;
public readonly amount: number;
constructor(origin: User, target: User, amount: number) {
this.date = Date.now();
this.origin = origin.id;
this.target = target.id;
this.amount = amount;
}
public changeTarget(user: User) {
this.target = user;
}
}
class TransactionManager {
private static instance: TransactionManager;
private transactions: Transaction[] = [];
private users: { [id: string]: User } = {};
public getInstance() {
if (!TransactionManager.instance) {
TransactionManager.instance = new TransactionManager();
}
return TransactionManager.instance;
}
public createUser(name) {
let user = new User(name);
this.users[user.id] = user;
return user;
}
public lendMoney(from: User, to: User, amount: number) {
let transaction = new Transaction(from, to, amount);
this.transactions = this.transactions.concat(transaction);
return transaction;
}
public getUserDept(user: User) {
if(!this.users[user.id]) {
throw new Error('user not found');
}
return this.transactions.reduce((dept: number, t: Transaction) => {
return t.origin === user.id ? dept + t.amount : dept;
}, 0);
}
}