forked from github/codespaces-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigital_wallet1.js
90 lines (76 loc) · 2.55 KB
/
digital_wallet1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Digital Wallet Implementation
class DigitalWallet {
constructor() {
this.users = {};
}
// Create a new user
createUser(username) {
if (this.users[username]) {
console.log("User already exists!");
return;
}
this.users[username] = { balance: 0 };
console.log(`User ${username} created successfully.`);
}
// Add money to a user's wallet
addMoney(username, amount) {
if (!this.users[username]) {
console.log("User does not exist!");
return;
}
if (amount <= 0) {
console.log("Amount should be greater than zero.");
return;
}
this.users[username].balance += amount;
console.log(`₹${amount} added to ${username}'s wallet. Current balance: ₹${this.users[username].balance}`);
}
// Transfer money between users
transferMoney(sender, receiver, amount) {
if (!this.users[sender]) {
console.log("Sender does not exist!");
return;
}
if (!this.users[receiver]) {
console.log("Receiver does not exist!");
return;
}
if (amount <= 0) {
console.log("Amount should be greater than zero.");
return;
}
if (this.users[sender].balance < amount) {
console.log("Insufficient balance in sender's wallet.");
return;
}
this.users[sender].balance -= amount;
this.users[receiver].balance += amount;
console.log(`₹${amount} transferred from ${sender} to ${receiver}.`);
console.log(`${sender}'s new balance: ₹${this.users[sender].balance}`);
console.log(`${receiver}'s new balance: ₹${this.users[receiver].balance}`);
}
// Check user's wallet balance
checkBalance(username) {
if (!this.users[username]) {
console.log("User does not exist!");
return;
}
console.log(`${username}'s wallet balance: ₹${this.users[username].balance}`);
}
}
// Example Usage
const wallet = new DigitalWallet();
// Create users
wallet.createUser("Alice");
wallet.createUser("Bob");
// Add money to wallet
wallet.addMoney("Alice", 1000);
wallet.addMoney("Bob", 500);
// Check balances
wallet.checkBalance("Alice");
wallet.checkBalance("Bob");
// Transfer money
wallet.transferMoney("Alice", "Bob", 200);
// Check balances again
wallet.checkBalance("Alice");
wallet.checkBalance("Bob");