forked from github/codespaces-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigital wallet.html
95 lines (86 loc) · 2.8 KB
/
digital wallet.html
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
91
92
93
94
95
// Simple Digital Wallet Implementation
class Wallet {
constructor() {
this.users = {}; // Stores user accounts
}
// Create a new user account
createAccount(username) {
if (this.users[username]) {
console.log(`Account for ${username} already exists.`);
return;
}
this.users[username] = { balance: 0 };
console.log(`Account created for ${username}.`);
}
// Deposit funds into a user's account
deposit(username, amount) {
if (!this.users[username]) {
console.log(`Account for ${username} does not exist.`);
return;
}
if (amount <= 0) {
console.log(`Deposit amount must be positive.`);
return;
}
this.users[username].balance += amount;
console.log(`${amount} deposited to ${username}'s account. Current balance: ${this.users[username].balance}`);
}
// Withdraw funds from a user's account
withdraw(username, amount) {
if (!this.users[username]) {
console.log(`Account for ${username} does not exist.`);
return;
}
if (amount <= 0) {
console.log(`Withdrawal amount must be positive.`);
return;
}
if (this.users[username].balance < amount) {
console.log(`Insufficient funds in ${username}'s account.`);
return;
}
this.users[username].balance -= amount;
console.log(`${amount} withdrawn from ${username}'s account. Current balance: ${this.users[username].balance}`);
}
// Transfer funds between two accounts
transfer(sender, receiver, amount) {
if (!this.users[sender]) {
console.log(`Sender account for ${sender} does not exist.`);
return;
}
if (!this.users[receiver]) {
console.log(`Receiver account for ${receiver} does not exist.`);
return;
}
if (amount <= 0) {
console.log(`Transfer amount must be positive.`);
return;
}
if (this.users[sender].balance < amount) {
console.log(`Insufficient funds in ${sender}'s account.`);
return;
}
this.users[sender].balance -= amount;
this.users[receiver].balance += amount;
console.log(`${amount} transferred from ${sender} to ${receiver}.`);
}
// Check the balance of a user's account
checkBalance(username) {
if (!this.users[username]) {
console.log(`Account for ${username} does not exist.`);
return;
}
console.log(`Current balance for ${username}: ${this.users[username].balance}`);
}
}
// Example Usage
const myWallet = new Wallet();
myWallet.createAccount('Alice');
myWallet.createAccount('Bob');
myWallet.deposit('Alice', 100);
myWallet.checkBalance('Alice');
myWallet.withdraw('Alice', 50);
myWallet.checkBalance('Alice');
myWallet.transfer('Alice', 'Bob', 25);
myWallet.checkBalance('Alice');
myWallet.checkBalance('Bob');