-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
814 lines (635 loc) · 23.4 KB
/
script.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
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
'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 displayMovements = function (movements, sort = false) {
containerMovements.innerHTML = '';
const movs = sort ? movements.slice().sort((a, b) => a - b) : movements;
movs.forEach(function (mov, i) {
const type = mov > 0 ? 'deposit' : 'withdrawal';
const html = `
<div class="movements__row">
<div class="movements__type movements__type--${type}">${
i + 1
} ${type}</div>
<div class="movements__value">${mov}€</div>
</div>`;
containerMovements.insertAdjacentHTML('afterbegin', html);
});
};
const calcDisplayBalance = function (acc) {
acc.balance = acc.movements.reduce((acc, mov) => acc + mov, 0);
labelBalance.textContent = `${acc.balance}€`;
};
const calcDisplaySummary = function (acc) {
const incomes = acc.movements
.filter(mov => mov > 0)
.reduce((acc, mov) => acc + mov, 0);
labelSumIn.textContent = `${incomes}€`;
const out = acc.movements
.filter(mov => mov < 0)
.reduce((acc, mov) => acc + mov, 0);
labelSumOut.textContent = `${Math.abs(out)}€`;
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 createUserNames = function (accs) {
accs.forEach(function (acc) {
acc.userName = acc.owner
.toLowerCase()
.split(' ')
.map(name => name[0])
.join('');
});
};
createUserNames(accounts);
const updateUI = function (acc) {
// Display movements
displayMovements(acc.movements);
// Display balance
calcDisplayBalance(acc);
// 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(accounts);
console.log(currentAccount);
if (currentAccount?.pin === Number(inputLoginPin.value)) {
// 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();
// Update UI
updateUI(currentAccount);
}
});
btnTransfer.addEventListener('click', function (event) {
event.preventDefault();
const amount = Number(inputTransferAmount.value);
const receiverAcc = accounts.find(
acc => acc.userName === inputTransferTo.value
);
inputTransferAmount.value = inputTransferTo.value = '';
if (
amount > 0 &&
receiverAcc &&
currentAccount.balance >= amount &&
receiverAcc?.userName !== currentAccount.userName
) {
// Doing the transfer
currentAccount.movements.push(-amount);
receiverAcc.movements.push(amount);
// Update UI
updateUI(currentAccount);
}
});
btnLoan.addEventListener('click', function (event) {
event.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 (event) {
event.preventDefault();
if (
currentAccount.userName === inputCloseUsername.value &&
currentAccount.pin === Number(inputClosePin.value)
) {
const index = accounts.findIndex(
acc => acc.userName === currentAccount.userName
);
console.log(index);
// Delete account
accounts.splice(index, 1);
// Hide UI
containerApp.style.opacity = 0;
}
inputCloseUsername.value = inputClosePin.value = '';
});
let sorted = false;
btnSort.addEventListener('click', function (event) {
event.preventDefault();
displayMovements(currentAccount.movements, !sorted);
sorted = !sorted;
});
/////////////////////////////////////////////////
/////////////////////////////////////////////////
// LECTURES
const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
/////////////////////////////////////////////////
// Simple Array Methods
/*
let arr = ['a', 'b', 'c', 'd', 'e'];
// Method: Slice
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]);
// Method: splice
// console.log(arr.splice(2));
arr.splice(-1);
console.log(arr);
arr.splice(1, 2);
console.log(arr);
// Method: reverse
arr = ['a', 'b', 'c', 'd', 'e'];
const arr2 = ['j', 'i', 'h', 'g', 'f'];
console.log(arr2.reverse());
console.log(arr2);
// Method: concat
const letters = arr.concat(arr2);
console.log(letters);
console.log([...arr, ...arr2]);
// Method: join
console.log(letters.join(', '));
*/
/////////////////////////////////////////////////
// Looping arrays: forEach
/*
const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
console.log(movements.entries());
// for (const movement of movements) {
for (const [i, movement] of movements.entries()) {
if (movement > 0) {
console.log(`Movement ${i + 1}: You deposited ${movement}`);
} else {
console.log(`Movement ${i + 1}: You withdrew ${Math.abs(movement)}`);
}
}
console.log('------ ForEach ------');
movements.forEach(function (mov, i, arr) {
if (mov > 0) {
console.log(`Movement ${i + 1}: You deposited ${mov}`);
} else {
console.log(`Movement ${i + 1}: You withdrew ${Math.abs(mov)}`);
}
});
// 0: function(200)
// 1: function(200)
// 2: function(200)
// ...
*/
/////////////////////////////////////////////////
// Looping arrays: forEach
/*
// Map
const currencies = new Map([
['USD', 'United States dollar'],
['EUR', 'Euro'],
['GBP', 'Pound sterling'],
]);
currencies.forEach(function (value, key, map) {
console.log(`${key}: ${value}`);
});
// Set
const currenciesUnique = new Set(['USD', 'GBP', 'USD', 'EUR', 'EUR']);
console.log(currenciesUnique);
currenciesUnique.forEach(function (value, _, map) {
console.log(`${value}: ${value}`);
});
*/
///////////////////////////////////////
// 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 dogsJulia = [3, 5, 2, 12, 7];
// const dogsKate = [4, 1, 15, 8, 3];
/*
const dogsJulia = [9, 16, 6, 8, 3];
const dogsKate = [10, 5, 6, 1, 4];
const checkDogs = function (arr1, arr2) {
const dogsJuliaFix = arr1.slice(1, 3);
const dogsTotal = [...dogsJuliaFix, ...arr2];
console.log(dogsTotal);
dogsTotal.forEach(function (age, i) {
if (age >= 3) {
console.log(`Dog number ${i + 1} is an adult, and is ${age} years old.`);
} else {
console.log(`Dog number ${i + 1} is still a puppy 🐶.`);
}
});
};
checkDogs(dogsJulia, dogsKate);
*/
/*
const eurToUsd = 1.21;
// const movementsUSD = movements.map(function (mov) {
// return mov * eurToUsd;
// });
const movementsUSD = movements.map(mov => mov * eurToUsd);
const movementsUSDfor = [];
for (const mov of movements) movementsUSDfor.push(mov * eurToUsd);
console.log(movements);
console.log(movementsUSD);
const movementsDescriptions = movements.map(
(mov, i) =>
`Movement ${i + 1}: You ${mov > 0 ? 'deposited' : 'withdrew'} ${Math.abs(
mov
)}`
);
console.log(movementsDescriptions);
*/
/////////////////////////////////////////////////
// The filter Method
/*
const deposits = movements.filter(function (mov, i, arr) {
return mov > 0;
});
console.log(movements);
console.log(deposits);
const depositsFor = [];
for (const mov of movements) if (mov > 0) depositsFor.push(mov);
console.log(depositsFor);
const withdrawals = movements.filter(mov => mov < 0);
console.log(withdrawals);
*/
/////////////////////////////////////////////////
// The reduce Method
/*
console.log(movements);
// accumulator -> SNOWBALL
// const balance = movements.reduce(function (acc, cur, i, arr) {
// console.log(`Iteration ${i}: ${acc}`);
// return acc + cur;
// }, 0);
const balance = movements.reduce((acc, cur) => acc + cur, 0);
console.log(balance);
let balance2 = 0;
for (const mov of movements) balance2 += mov;
console.log(balance2);
// Maximum value
const max = movements.reduce((acc, mov) => {
if (acc > mov) {
return acc;
} else {
return mov;
}
}, movements[0]);
console.log(max);
*/
///////////////////////////////////////
// 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 ages = [5, 2, 4, 1, 15, 8, 3];
const ages2 = [16, 6, 10, 5, 6, 1, 4];
const calculator = function (dogAges) {
const calcAverageHumanAge = dogAges
.map(dogAge => (dogAge <= 2 ? dogAge * 2 : 16 + dogAge * 4))
.filter(humanAge => humanAge >= 18)
.reduce((acc, cur, i, arr) => acc + cur / arr.length, 0);
return calcAverageHumanAge;
};
const avg1 = calculator(ages);
const avg2 = calculator(ages2);
console.log(avg1, avg2);
*/
///////////////////////////////////////
// Coding Challenge #2
/*
const eurToUsd = 1.1;
// Pipeline
const totalDepositUSD = movements
.filter(mov => mov > 0)
.map(mov => mov * eurToUsd)
.reduce((acc, mov) => acc + mov, 0);
console.log(totalDepositUSD);
*/
///////////////////////////////////////
// Coding Challenge #3
/*
Rewrite the 'calcAverageHumanAge' function from the previous challenge, but this time as an arrow function, and using chaining!
TEST DATA 1: [5, 2, 4, 1, 15, 8, 3]
TEST DATA 2: [16, 6, 10, 5, 6, 1, 4]
GOOD LUCK 😀
*/
/*
const ages = [5, 2, 4, 1, 15, 8, 3];
const ages2 = [16, 6, 10, 5, 6, 1, 4];
const calculator = function (dogAges) {
const calcAverageHumanAge = dogAges
.map(dogAge => (dogAge <= 2 ? dogAge * 2 : 16 + dogAge * 4))
.filter(humanAge => humanAge >= 18)
.reduce((acc, cur, i, arr) => acc + cur / arr.length, 0);
return calcAverageHumanAge;
};
const avg1 = calculator(ages);
const avg2 = calculator(ages2);
console.log(avg1, avg2);
*/
///////////////////////////////////////
// 155. The 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);
*/
///////////////////////////////////////
// 159. some and every
/*
console.log(movements);
// Equality
console.log(movements.includes(-130));
// Some: Condition
console.log(movements.some(mov => mov === -130));
const anyDeposits = movements.some(mov => mov > 0);
console.log(anyDeposits);
// Every
console.log(movements.every(mov => mov > 0));
console.log(account4.movements.every(mov => mov > 0));
// Separate Callback
const deposit = mov => mov > 0;
console.log(movements.some(deposit));
console.log(movements.every(deposit));
console.log(movements.filter(deposit));
*/
///////////////////////////////////////
// 160. flat and flatMap
/*
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(arr.flat());
// flat
const overalBalance = accounts
.map(acc => acc.movements)
.flat()
.reduce((acc, mov) => acc + mov, 0);
console.log(overalBalance);
// flatMap
const overalBalance2 = accounts
.flatMap(acc => acc.movements)
.reduce((acc, mov) => acc + mov, 0);
console.log(overalBalance2);
*/
///////////////////////////////////////
// 161. Sorting Arrays
/*
// Strings
const owners = ['Jonas', 'Zach', 'Adam', 'Martha'];
console.log(owners.sort());
console.log(owners);
// Numbers
console.log(movements);
// return < 0, A, B (keep order)
// return < 0, B, A (switch order)
// Ascending
// movements.sort((a, b) => {
// if (a > b) return 1;
// if (a < b) return -1;
// });
movements.sort((a, b) => a - b);
console.log(movements);
// Descending
// movements.sort((a, b) => {
// if (a > b) return -1;
// if (a < b) return 1;
// });
movements.sort((a, b) => b - a);
console.log(movements);
*/
///////////////////////////////////////
// 162. More Ways of Creating and Filling Arrays
/*
const arr = [1, 2, 3, 4, 5, 6, 7];
console.log(new Array(1, 2, 3, 4, 5, 6, 7));
// Emprty arrays + fill method
const x = new Array(7);
console.log(x);
// console.log(x.map(() => 5));
x.fill(1, 3, 5);
x.fill(1);
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 }, (currentElement, index) => index + 1);
console.log(z);
labelBalance.addEventListener('click', function () {
const movementsUI = Array.from(
document.querySelectorAll('.movements__value'),
element => Number(element.textContent.replace('€', ''))
);
console.log(movementsUI);
const movementsUI2 = [...document.querySelectorAll('.movements__value')];
console.log(movementsUI2);
});
*/
///////////////////////////////////////
// 164. Array Methods Practice
/*
// 1.
const bankDepositSum = accounts
.flatMap(acc => acc.movements)
.filter(mov => mov > 0)
.reduce((sum, cur) => sum + cur, 0);
console.log(bankDepositSum);
// 2.
// const numDeposits1000 = accounts
// .flatMap(acc => acc.movements)
// .filter(mov => mov >= 1000).length;
const numDeposits1000 = accounts
.flatMap(acc => acc.movements)
.reduce((count, cur) => (cur >= 1000 ? count + 1 : count), 0);
console.log(numDeposits1000);
// Prefixed ++ operator
let a = 10;
console.log(++a);
console.log(a);
// 3.
const { deposits, withdrawals } = accounts
.flatMap(acc => acc.movements)
.reduce(
(sums, cur) => {
// cur > 0 ? (sums.deposits += cur) : (sums.withdrawals += cur);
sums[cur > 0 ? 'deposits' : 'withdrawals'] += cur;
return sums;
},
{ deposits: 0, withdrawals: 0 }
);
console.log(deposits, withdrawals);
// 4.
// this is a nice title -> This Is a Nice Title
const convertTitleCase = function (title) {
const capitzalize = str => str[0].toUpperCase() + str.slice(1);
const exceptions = ['a', 'an', 'and', 'the', 'but', 'or', 'on', 'in', 'with'];
const titleCase = title
.toLowerCase()
.split(' ')
.map(word => (exceptions.includes(word) ? word : capitzalize(word)))
.join(' ');
return capitzalize(titleCase);
};
console.log(convertTitleCase('this is a nice title'));
console.log(convertTitleCase('this is a LONG title but not too long'));
console.log(convertTitleCase('and here is another title with an EXAMPLE'));
*/
///////////////////////////////////////
// 165. Coding Challenge #4
/*
Julia and Kate are still studying dogs, and this time they are studying if dogs are eating too much or too little.
Eating too much means the dog's current food portion is larger than the recommended portion, and eating too little is the opposite.
Eating an okay amount means the dog's current food portion is within a range 10% above and 10% below the recommended portion (see hint).
1. Loop over the array containing dog objects, and for each dog, calculate the recommended food portion and add it to the object as a new property. Do NOT create a new array, simply loop over the array. Forumla: recommendedFood = weight ** 0.75 * 28. (The result is in grams of food, and the weight needs to be in kg)
2. Find Sarah's dog and log to the console whether it's eating too much or too little. HINT: Some dogs have multiple owners, so you first need to find Sarah in the owners array, and so this one is a bit tricky (on purpose) 🤓
3. Create an array containing all owners of dogs who eat too much ('ownersEatTooMuch') and an array with all owners of dogs who eat too little ('ownersEatTooLittle').
4. Log a string to the console for each array created in 3., like this: "Matilda and Alice and Bob's dogs eat too much!" and "Sarah and John and Michael's dogs eat too little!"
5. Log to the console whether there is any dog eating EXACTLY the amount of food that is recommended (just true or false)
6. Log to the console whether there is any dog eating an OKAY amount of food (just true or false)
7. Create an array containing the dogs that are eating an OKAY amount of food (try to reuse the condition used in 6.)
8. Create a shallow copy of the dogs array and sort it by recommended food portion in an ascending order (keep in mind that the portions are inside the array's objects)
HINT 1: Use many different tools to solve these challenges, you can use the summary lecture to choose between them 😉
HINT 2: Being within a range 10% above and below the recommended portion means: current > (recommended * 0.90) && current < (recommended * 1.10). Basically, the current portion should be between 90% and 110% of the recommended portion.
TEST DATA:
const dogs = [
{ weight: 22, curFood: 250, owners: ['Alice', 'Bob'] },
{ weight: 8, curFood: 200, owners: ['Matilda'] },
{ weight: 13, curFood: 275, owners: ['Sarah', 'John'] },
{ weight: 32, curFood: 340, owners: ['Michael'] }
];
GOOD LUCK 😀
*/
const dogs = [
{ weight: 22, curFood: 250, owners: ['Alice', 'Bob'] },
{ weight: 8, curFood: 200, owners: ['Matilda'] },
{ weight: 13, curFood: 275, owners: ['Sarah', 'John'] },
{ weight: 32, curFood: 340, owners: ['Michael'] },
];
// 1. Loop over the array containing dog objects, and for each dog, calculate the recommended food portion and add it to the object as a new property. Do NOT create a new array, simply loop over the array. Forumla: recommendedFood = weight ** 0.75 * 28. (The result is in grams of food, and the weight needs to be in kg).
dogs.forEach(
dog => (dog.recommendedFood = Math.round(dog.weight ** 0.75 * 28))
);
console.log(dogs);
// 2. Find Sarah's dog and log to the console whether it's eating too much or too little. HINT: Some dogs have multiple owners, so you first need to find Sarah in the owners array, and so this one is a bit tricky (on purpose) 🤓
const sarahDog = dogs.find(dog => dog.owners.includes('Sarah'));
console.log(
`Sarah's dog is eating too ${
sarahDog.curFood > sarahDog.recommendedFood ? 'much' : 'little'
}`
);
// 3. Create an array containing all owners of dogs who eat too much ('ownersEatTooMuch') and an array with all owners of dogs who eat too little ('ownersEatTooLittle').
const ownersEatTooMuch = dogs
.filter(dog => dog.curFood > dog.recommendedFood)
.map(dog => dog.owners)
.flat();
const ownersEatTooLittle = dogs
.filter(dog => dog.curFood < dog.recommendedFood)
.map(dog => dog.owners)
.flat();
console.log(ownersEatTooMuch, ownersEatTooLittle);
// 4. Log a string to the console for each array created in 3., like this: "Matilda and Alice and Bob's dogs eat too much!" and "Sarah and John and Michael's dogs eat too little!"
console.log(`${ownersEatTooMuch.join(' and ')}'s dogs eat too much!`);
console.log(`${ownersEatTooLittle.join(' and ')}'s dogs eat too little!`);
// 5. Log to the console whether there is any dog eating EXACTLY the amount of food that is recommended (just true or false)
console.log(dogs.some(dog => dog.curFood === dog.recommendedFood));
// 6. Log to the console whether there is any dog eating an OKAY amount of food (just true or false)
const checkEatingOkay = dog =>
dog.curFood > dog.recommendedFood * 0.9 &&
dog.curFood < dog.recommendedFood * 1.1;
console.log(dogs.some(checkEatingOkay));
// 7. Create an array containing the dogs that are eating an OKAY amount of food (try to reuse the condition used in 6.)
console.log(dogs.filter(checkEatingOkay));
// 8. Create a shallow copy of the dogs array and sort it by recommended food portion in an ascending order (keep in mind that the portions are inside the array's objects)
const dogsByOrder = dogs
.slice()
.sort((a, b) => a.recommendedFood - b.recommendedFood);
console.log(dogsByOrder);