-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
583 lines (468 loc) Β· 15.9 KB
/
Copy pathscript.js
File metadata and controls
583 lines (468 loc) Β· 15.9 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
'use strict';
/////////////////////////////////////////////////
/////////////////////////////////////////////////
// BANKIST APP
// Data
const account1 = {
owner: 'Jonas Schmedtmann',
movements: [200, 450, -400, 3000, -650, -130, 70, 1300],
interestRate: 1.2, // %
pin: 1111,
};
const account2 = {
owner: 'Jessica Davis',
movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30],
interestRate: 1.5,
pin: 2222,
};
const account3 = {
owner: 'Steven Thomas Williams',
movements: [200, -200, 340, -300, -20, 50, 400, -460],
interestRate: 0.7,
pin: 3333,
};
const account4 = {
owner: 'Sarah Smith',
movements: [430, 1000, 700, 50, 90],
interestRate: 1,
pin: 4444,
};
const accounts = [account1, account2, account3, account4];
// Elements
const labelWelcome = document.querySelector('.welcome');
const labelDate = document.querySelector('.date');
const labelBalance = document.querySelector('.balance__value');
const labelSumIn = document.querySelector('.summary__value--in');
const labelSumOut = document.querySelector('.summary__value--out');
const labelSumInterest = document.querySelector('.summary__value--interest');
const labelTimer = document.querySelector('.timer');
const containerApp = document.querySelector('.app');
const containerMovements = document.querySelector('.movements');
const btnLogin = document.querySelector('.login__btn');
const btnTransfer = document.querySelector('.form__btn--transfer');
const btnLoan = document.querySelector('.form__btn--loan');
const btnClose = document.querySelector('.form__btn--close');
const btnSort = document.querySelector('.btn--sort');
const inputLoginUsername = document.querySelector('.login__input--user');
const inputLoginPin = document.querySelector('.login__input--pin');
const inputTransferTo = document.querySelector('.form__input--to');
const inputTransferAmount = document.querySelector('.form__input--amount');
const inputLoanAmount = document.querySelector('.form__input--loan-amount');
const inputCloseUsername = document.querySelector('.form__input--user');
const inputClosePin = document.querySelector('.form__input--pin');
const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
const displayMovements = function (movements, sort = false) {
containerMovements.innerHTML = '';
const movs = sort ? movements.slice().sort((a, b) => a - b) : movements;
movs.forEach((mov, i) => {
let type = mov > 0 ? 'deposit' : 'withdrawal';
const html = `<div class="movements__row">
<div class="movements__type movements__type--${type}">${i + 1} deposit</div>
<div class="movements__date">3 days ago</div>
<div class="movements__value">${mov} β¬</div>
</div>`;
containerMovements.insertAdjacentHTML('afterbegin', html);
});
};
const calcDisplayBalance = function (movements) {
currentAccount.balance = movements.reduce((acc, mov) => acc + mov, 0);
labelBalance.textContent = `${currentAccount.balance} β¬`;
};
const calcDisplaySummary = function (acc) {
let incomes = acc.movements
.filter(mov => mov > 0)
.reduce((acc, curr) => acc + curr, 0);
labelSumIn.textContent = `${incomes}β¬`;
const outcomes = acc.movements
.filter(mov => mov < 0)
.reduce((acc, curr) => acc + curr);
labelSumOut.textContent = `${Math.abs(outcomes)}β¬`;
const interest = acc.movements
.filter(mov => mov > 0)
.map(deposit => (deposit * acc.interestRate) / 100)
.filter((int, i, arr) => {
// console.log(arr);
return int >= 1;
})
.reduce((acc, int) => acc + int, 0);
labelSumInterest.textContent = `${interest}β¬`;
};
const createUsersnames = function (accs) {
accs.forEach(function (acc) {
acc.username = acc.owner
.toLowerCase()
.split(' ')
.map(name => name[0])
.join('');
});
};
createUsersnames(accounts);
const UpdateUI = function (acc) {
//Display Movements
displayMovements(acc.movements);
// //Display balance
calcDisplayBalance(acc.movements);
//Display summary
calcDisplaySummary(acc);
};
//Event handler
let currentAccount;
btnLogin.addEventListener('click', function (e) {
//Prevent form from submitting
e.preventDefault();
currentAccount = accounts.find(
acc => acc.username === inputLoginUsername.value
);
console.log(currentAccount);
if (currentAccount?.pin === Number(inputLoginPin.value)) {
console.log('welcome user');
// Display UI and message
labelWelcome.textContent = `Welcome back, ${
currentAccount.owner.split(' ')[0]
}`;
containerApp.style.opacity = 100;
//Clear input fields
inputLoginUsername.value = inputLoginPin.value = '';
inputLoginPin.blur();
UpdateUI(currentAccount);
console.log(currentAccount.movements);
}
});
btnTransfer.addEventListener('click', function (e) {
e.preventDefault();
const amount = Number(inputTransferAmount.value);
const recieverACC = accounts.find(
acc => acc.username === inputTransferTo.value
);
inputTransferAmount.value = inputTransferTo.value = '';
if (
amount > 0 &&
recieverACC &&
currentAccount.balance >= amount &&
recieverACC?.user !== currentAccount.username
) {
//Doing the transfer
currentAccount.movements.push(-amount);
recieverACC.movements.push(amount);
//Update UI
UpdateUI(currentAccount);
}
});
btnLoan.addEventListener('click', function (e) {
e.preventDefault();
const amount = Number(inputLoanAmount.value);
if (amount > 0 && currentAccount.movements.some(mov => mov >= amount * 0.1)) {
//Add movement
currentAccount.movements.push(amount);
//Update UI
UpdateUI(currentAccount);
}
inputLoanAmount.value = '';
});
btnClose.addEventListener('click', function (e) {
e.preventDefault();
if (
inputCloseUsername.value === currentAccount.username &&
Number(inputClosePin.value) === currentAccount.pin
) {
const index = accounts.findIndex(
acc => acc.username === currentAccount.username
);
console.log(index);
// .indexOf(23)
//Delete account
accounts.splice(index, 1);
//Hide UI
containerApp.style.opacity = 0;
}
inputCloseUsername.value = inputClosePin.value = '';
});
let sorted = false;
btnSort.addEventListener('click', function (e) {
e.preventDefault();
displayMovements(currentAccount.movements, !sorted);
sorted = !sorted;
});
/////////////////////////////////////////////////
/////////////////////////////////////////////////
//LECTURES
//HOW TO PROGRAMATICALLY CREATE AND FILL AN ARRAY.
const arr = [1, 2, 3, 4, 5, 6, 7];
console.log(new Array(1, 2, 3, 4, 5, 6, 7));
const x = new Array(7);
console.log(x);
// x.fill(1);
x.fill(1, 3, 5);
console.log(x);
arr.fill(23, 2, 6);
console.log(arr);
//Array.from
const y = Array.from({ length: 7 }, () => 1);
console.log(y);
const z = Array.from({ length: 7 }, (_, i) => i + 1);
console.log(z);
//Create an array that generates 100 random dice rolls.
const randomDiceArray = Array.from(
{ length: 100 },
(_, i) => (i = Math.floor(Math.random() * 6) + 1)
);
console.log(randomDiceArray);
//SORTING : the sort method mutates the array.
//STRINGS
// const owners = ['Jonas', 'Zach', 'Adam', 'Martha'];
// console.log(owners.sort());
// console.log(owners);
//NUMBERS
// console.log(movements);
// return < 0, A, B
// return > 0, B, A (Switch order)
//Ascending
// movements.sort((a,b) => {
// if(a > b)
// return 1;
// if(b > a)
// return -1;
// })
// movements.sort((a,b) => a - b);
// console.log(movements);
//Descending
// movements.sort((a,b) => {
// if(a > b)
// return -1;
// if(b > a)
// return 1;
// })
// movements.sort((a,b) => b - a);
// console.log(movements);
//FLAT AND FLATMAP METHOD
// const arr = [[1, 2, 3], [4, 5, 6], 7, 8];
// console.log(arr.flat());
// const arrDeep = [[[1,2],3],[4,[5,6]], 7, 8];
// console.log(arrDeep.flat(2));
// const accountMovements = accounts.map(acc => acc.movements);
// console.log(accountMovements);
// const allMovements = accountMovements.flat();
// console.log(allMovements);
// const overalBalance = accounts
// .map(acc => acc.movements)
// .flat()
// .reduce((acc,cur) => acc + cur, 0);
// console.log(overalBalance);
// flatmap
// const overalBalance1 = accounts
// .flatMap(acc => acc.movements)
// .reduce((acc,cur) => acc + cur, 0);
// console.log(overalBalance1);
// EVERY
// console.log(movements.every(mov => mov > 0));
// console.log(account4.movements.every(mov => mov > 0));
//seperate callback
// const deposit = mov => mov > 0;
// console.log(movements.some(deposit));
// console.log(movements.every(deposit));
// console.log(movements.filter(deposit));
//THE SOME AND EVERY METHOD
// console.log(movements);
// //EQUALITY
// console.log(movements.includes(-130));
// // CONDITION
// console.log(movements.some(mov => mov === -130));
// const anyDeposit = movements.some(mov => mov > 1500);
// console.log(anyDeposit);
/*
//FIND METHOD
const firstWithdrawal = movements.find(mov => mov < 0);
console.log(movements);
console.log(firstWithdrawal);
console.log(accounts);const account = accounts.find(acc => acc.owner === 'Jessica Davis');
console.log(account);
*/
//////////////////////////////////////////////
// Code challengee #3
/*
Rewrite the 'calcAverageHumanAge' function from previous challenge, but these time as an arrow function using chaining
TEST DATA: [5, 2, 4, 1, 15, 8, 3]
TEST DATA: [16, 6, 10, 5, 6, 1, 4]
GOOD LUCK
*/
// const calcAverageHumanAge = (arr) => arr.reduce((acc, curr, i, arr) => acc + curr / arr.length,0);
// console.log(calcAverageHumanAge([5, 2, 4, 1, 15, 8, 3]));
/*
const eurToUsd = 1.1;
const totalDepositeUSD = movements
.filter(mov => mov > 0)
.map(mov => mov * eurToUsd)
.reduce((acc,curr) => acc + curr, 0);
console.log(totalDepositeUSD);
*/
///////////////////////////////////////
// Coding Challenge #2
/*
Let's go back to Julia and Kate's study about dogs. This time, they want to convert dog ages to human ages and calculate the average age of the dogs in their study.
Create a function 'calcAverageHumanAge', which accepts an arrays of dog's ages ('ages'), and does the following things in order:
1. Calculate the dog age in human years using the following formula: if the dog is <= 2 years old, humanAge = 2 * dogAge. If the dog is > 2 years old, humanAge = 16 + dogAge * 4.
2. Exclude all dogs that are less than 18 human years old (which is the same as keeping dogs that are at least 18 years old)
3. Calculate the average human age of all adult dogs (you should already know from other challenges how we calculate averages π)
4. Run the function for both test datasets
TEST DATA 1: [5, 2, 4, 1, 15, 8, 3]
TEST DATA 2: [16, 6, 10, 5, 6, 1, 4]
GOOD LUCK π
*/
/*
const calcAverageHumanAge = function(ages) {
const humanAges = ages.map(dogAge => dogAge <= 2 ? 2 * dogAge : 16 + dogAge * 4
).filter((age) => age >= 18).reduce((acc, cur, i, arr) => (acc + cur) / arr.length, arr[0]);
console.log(humanAges);
// console.log(humanAges);
// const adults = humanAges.filter((age) => age >= 18)
// console.log(adults);
// const average = adults.reduce((acc, cur) => (acc + cur) / adults.length, adults[0]);
// console.log(average);
};
calcAverageHumanAge([5, 2, 4, 1, 15, 8, 3]);
calcAverageHumanAge([16, 6, 10, 5, 6, 1, 4]);
*/
//DATA TRANSFORMATIONS: MAP, FILTER, REDUCE
/*
//REDUCE
const balance = movements.reduce(function(acc, curr, i, arr) {
console.log(`Iteration ${i}: ${acc}`);
return acc + curr;
}, 0);
console.log(balance);
//MAXIMUM VALUE
const max = movements.reduce((acc, curr) => acc > curr ? acc: curr
, movements[0]);
console.log(max);
*/
// let balances = 0;
// for(const mov of movements) {
// balances += mov;
// };
// console.log(balances);
/*
//FILTER
const deposits = movements.filter(function(mov) {
return mov > 0;
});
console.log(movements);
console.log(deposits);
const withdrawals = movements.filter(mov => mov < 0
);
console.log(withdrawals);
*/
//MAP
//The map method is yet another method we can use to loop over arrays. the map method creates a new array based on the original array.
// const original = [3, 1, 4, 3, 2];
// original.map((current) => {
// console.log(current * 2)
// })
// const euroToUsd = 1.1;
// const movementUSD = movements.map(mov => Math.trunc(mov * euroToUsd)
// );
// console.log(movements);
// console.log(movementUSD);
// const movementDescriptions = movements.map((mov, i, arr) =>
// `Movement: ${i + 1}: You ${mov > 0 ? 'deposited' : 'withdrew'} ${Maths.abs(mov)}`
// );
// console.log(movementDescriptions);
///////////////////////////////////////
// Coding Challenge #1
/*
Julia and Kate are doing a study on dogs. So each of them asked 5 dog owners about their dog's age, and stored the data into an array (one array for each). For now, they are just interested in knowing whether a dog is an adult or a puppy. A dog is an adult if it is at least 3 years old, and it's a puppy if it's less than 3 years old.
Create a function 'checkDogs', which accepts 2 arrays of dog's ages ('dogsJulia' and 'dogsKate'), and does the following things:
1. Julia found out that the owners of the FIRST and the LAST TWO dogs actually have cats, not dogs! So create a shallow copy of Julia's array, and remove the cat ages from that copied array (because it's a bad practice to mutate function parameters)
2. Create an array with both Julia's (corrected) and Kate's data
3. For each remaining dog, log to the console whether it's an adult ("Dog number 1 is an adult, and is 5 years old") or a puppy ("Dog number 2 is still a puppy πΆ")
4. Run the function for both test datasets
HINT: Use tools from all lectures in this section so far π
TEST DATA 1: Julia's data [3, 5, 2, 12, 7], Kate's data [4, 1, 15, 8, 3]
TEST DATA 2: Julia's data [9, 16, 6, 8, 3], Kate's data [10, 5, 6, 1, 4]
GOOD LUCK π
*/
/*
const checkDogs = function(dogsJulia, dogKate) {
const juliasCorrect = dogsJulia.slice(1, 3);
const corrected = [...juliasCorrect, ...dogKate];
console.log(corrected);
corrected.forEach((dog, i) => {
if(dog >= 3) {
console.log(`Dog number ${i + 1} is an adult and is ${dog} years old`);
} else {
console.log(`Dog number ${i + 1} is an adult and is ${dog} years old`);
}
});
};
checkDogs([3, 5, 2, 12, 7], [4, 1, 15, 8, 3]);
checkDogs([9, 16, 6, 8, 3], [10, 5, 6, 1, 4]);
*/
// const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
/////////////////////////////////////////////////
/*
//SLICE METHOD
let arr = ['a', 'b', 'c', 'd', 'e'];
console.log(arr.slice(2));
console.log(arr.slice(2,4));
console.log(arr.slice(-2));
console.log(arr.slice(-1));
console.log(arr.slice(1,-2));
console.log(arr.slice());
console.log([...arr]);
//SPLICE METHOD
// console.log(arr.splice(2));
arr.splice(-1);
console.log(arr);
arr.splice(1,2);
console.log(arr);
//REVERSE
arr = ['a', 'b', 'c', 'd', 'e'];
const arr2 = ['j', 'i', 'g', 'h', 'f', 'e'];
console.log(arr2.reverse());
console.log(arr2);
//CONCAT
const letters = arr.concat(arr2);
console.log(letters);
console.log([...arr,...arr2]);
//JOIN
console.log(letters.join(' - '));
*/
/*
const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
for(const [i, movement] of movements.entries()) {
if(movement > 0) {
console.log(`Movement: ${i + 1}you deposited ${movement}`);
} else {
console.log(`you withdrew ${Math.abs(movement)}`);
}
};
movements.forEach((movement, i, arr) => {
if(movement > 0) {
console.log(`Movement: ${i + 1} you deposited ${movement}`);
} else {
console.log(`you withdrew ${Math.abs(movement)}`);
}
});
// for (const i = 0; i < movements.length; i++) {
// let movement = movements[i];
// if(movement > 0) {
// console.log(`you deposited ${movement}`);
// } else {
// console.log(`you withdrew ${Math.abs(movement)}`);
// }
// };
//
const currencies = new Map([
['USD', 'United States dollar'],
['EUR', 'Euro'],
['GBP', 'Pound sterling'],
]);
currencies.forEach((value, key, map) => {
console.log(`${key}: ${value}`);
});
//SET
const currenciesUnique = new Set (['USD', 'GBP', 'USD', 'EUR', 'EUR']);
console.log(currenciesUnique);
currenciesUnique.forEach((value, key, map) => {
console.log(`${value}: ${value}`);
});
*/