Careeroza
Real World Example
A Wallet Like Paytm or PhonePe
Digital wallets keep a balance and a transaction history. A class groups the data and the rules (no negative balance, every change is recorded) in one place.
Example
type Txn = { type: "CREDIT" | "DEBIT"; amount: number; note: string };
class Wallet {
private history: Txn[] = [];
constructor(public readonly owner: string, private balance = 0) {}
addMoney(amount: number, note = "Top-up"): void {
this.balance += amount;
this.history.push({ type: "CREDIT", amount, note });
}
pay(amount: number, note: string): boolean {
if (amount > this.balance) {
console.log(`Payment of Rs. ${amount} to ${note} failed: low balance`);
return false;
}
this.balance -= amount;
this.history.push({ type: "DEBIT", amount, note });
return true;
}
statement(): void {
for (const t of this.history) {
console.log(t.type.padEnd(6), String(t.amount).padStart(6), t.note);
}
console.log("Balance:", this.balance);
}
}
const w = new Wallet("Rohit");
w.addMoney(1000);
w.pay(249, "Swiggy");
w.pay(900, "Electricity bill");
w.pay(120, "Metro card");
w.statement();Output
Payment of Rs. 900 to Electricity bill failed: low balance CREDIT 1000 Top-up DEBIT 249 Swiggy DEBIT 120 Metro card Balance: 631