Ismail Ismail - 1 year ago 54
Node.js Question

object for my simple money recording app

I am trying to make an app where people owe money to each other. let say person buy movies tickets for his friends and each ticket cost was 20 dollar. Now every one of his friend owe that person 20$.

I did made an object but, i think it is not right way to approach it. I would like know if there is a better way i can do it.

for Example
person1 to person2: $20.
person3 to person2: $20.
person2 to person1: $0.
person2 to person3: $0.

i have approached like this

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}]);

Answer Source

I wouldn't recommend to tie the "transactions" to the user itself. Keep them separately. Maybe just like this.

// 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);
  }
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download