forked from jonasschmedtmann/complete-javascript-course
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
executable file
·730 lines (495 loc) · 14.6 KB
/
Copy pathscript.js
File metadata and controls
executable file
·730 lines (495 loc) · 14.6 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
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
/////////////////////////////////
// Lecture: let and const
/*
// ES5
var name5 = 'Jane Smith';
var age5 = 23;
name5 = 'Jane Miller';
console.log(name5);
// ES6
const name6 = 'Jane Smith';
let age6 = 23;
name6 = 'Jane Miller';
console.log(name6);
// ES5
function driversLicence5(passedTest) {
if (passedTest) {
console.log(firstName);
var firstName = 'John';
var yearOfBirth = 1990;
}
console.log(firstName + ', born in ' + yearOfBirth + ', is now officially allowed to drive a car.');
}
driversLicence5(true);
// ES6
function driversLicence6(passedTest) {
//console.log(firstName);
let firstName;
const yearOfBirth = 1990;
if (passedTest) {
firstName = 'John';
}
console.log(firstName + ', born in ' + yearOfBirth + ', is now officially allowed to drive a car.');
}
driversLicence6(true);
var i = 23;
for (var i = 0; i < 5; i++) {
console.log(i);
}
console.log(i);
*/
/////////////////////////////////
// Lecture: Blocks and IIFEs
/*
// ES6
{
const a = 1;
let b = 2;
var c = 3;
}
//console.log(a + b);
console.log(c);
// ES5
(function() {
var c = 3;
})();
//console.log(c);
*/
/////////////////////////////////
// Lecture: Strings
/*
let firstName = 'John';
let lastName = 'Smith';
const yearOfBirth = 1990;
function calcAge(year) {
return 2016 - year;
}
// ES5
console.log('This is ' + firstName + ' ' + lastName + '. He was born in ' + yearOfBirth + '. Today, he is ' + calcAge(yearOfBirth) + ' years old.');
// ES6
console.log(`This is ${firstName} ${lastName}. He was born in ${yearOfBirth}. Today, he is ${calcAge(yearOfBirth)} years old.`);
const n = `${firstName} ${lastName}`;
console.log(n.startsWith('j'));
console.log(n.endsWith('Sm'));
console.log(n.includes('oh'));
console.log(`${firstName} `.repeat(5));
*/
/////////////////////////////////
// Lecture: Arrow functions
/*
const years = [1990, 1965, 1982, 1937];
// ES5
var ages5 = years.map(function(el) {
return 2016 - el;
});
console.log(ages5);
// ES6
let ages6 = years.map(el => 2016 - el);
console.log(ages6);
ages6 = years.map((el, index) => `Age element ${index + 1}: ${2016 - el}.`);
console.log(ages6);
ages6 = years.map((el, index) => {
const now = new Date().getFullYear();
const age = now - el;
return `Age element ${index + 1}: ${age}.`
});
console.log(ages6);
*/
/////////////////////////////////
// Lecture: Arrow functions 2
/*
// ES5
var box5 = {
color: 'green',
position: 1,
clickMe: function() {
var self = this; document.querySelector('.green').addEventListener('click', function() {
var str = 'This is box number ' + self.position + ' and it is ' + self.color;
alert(str);
});
}
}
//box5.clickMe();
// ES6
const box6 = {
color: 'green',
position: 1,
clickMe: function() {
document.querySelector('.green').addEventListener('click', () => {
var str = 'This is box number ' + this.position + ' and it is ' + this.color;
alert(str);
});
}
}
box6.clickMe();
const box66 = {
color: 'green',
position: 1,
clickMe: () => {
document.querySelector('.green').addEventListener('click', () => {
var str = 'This is box number ' + this.position + ' and it is ' + this.color;
alert(str);
});
}
}
box66.clickMe();
function Person(name) {
this.name = name;
}
// ES5
Person.prototype.myFriends5 = function(friends) {
var arr = friends.map(function(el) {
return this.name + ' is friends with ' + el;
}.bind(this));
console.log(arr);
}
var friends = ['Bob', 'Jane', 'Mark'];
new Person('John').myFriends5(friends);
// ES6
Person.prototype.myFriends6 = function(friends) {
var arr = friends.map(el => `${this.name} is friends with ${el}`);
console.log(arr);
}
new Person('Mike').myFriends6(friends);
*/
/////////////////////////////////
// Lecture: Destructuring
/*
// ES5
var john = ['John', 26];
//var name = john[0];
//var age = john[1];
// ES6
const [name, age] = ['John', 26];
console.log(name);
console.log(age);
const obj = {
firstName: 'John',
lastName: 'Smith'
};
const {firstName, lastName} = obj;
console.log(firstName);
console.log(lastName);
const {firstName: a, lastName: b} = obj;
console.log(a);
console.log(b);
function calcAgeRetirement(year) {
const age = new Date().getFullYear() - year;
return [age, 65 - age];
}
const [age2, retirement] = calcAgeRetirement(1990);
console.log(age2);
console.log(retirement);
*/
/////////////////////////////////
// Lecture: Arrays
/*
const boxes = document.querySelectorAll('.box');
//ES5
var boxesArr5 = Array.prototype.slice.call(boxes);
boxesArr5.forEach(function(cur) {
cur.style.backgroundColor = 'dodgerblue';
});
//ES6
const boxesArr6 = Array.from(boxes);
Array.from(boxes).forEach(cur => cur.style.backgroundColor = 'dodgerblue');
//ES5
for(var i = 0; i < boxesArr5.length; i++) {
if(boxesArr5[i].className === 'box blue') {
continue;
}
boxesArr5[i].textContent = 'I changed to blue!';
}
//ES6
for (const cur of boxesArr6) {
if (cur.className.includes('blue')) {
continue;
}
cur.textContent = 'I changed to blue!';
}
//ES5
var ages = [12, 17, 8, 21, 14, 11];
var full = ages.map(function(cur) {
return cur >= 18;
});
console.log(full);
console.log(full.indexOf(true));
console.log(ages[full.indexOf(true)]);
//ES6
console.log(ages.findIndex(cur => cur >= 18));
console.log(ages.find(cur => cur >= 18));
*/
/////////////////////////////////
// Lecture: Spread operator
/*
function addFourAges (a, b, c, d) {
return a + b + c + d;
}
var sum1 = addFourAges(18, 30, 12, 21);
console.log(sum1);
//ES5
var ages = [18, 30, 12, 21];
var sum2 = addFourAges.apply(null, ages);
console.log(sum2);
//ES6
const sum3 = addFourAges(...ages);
console.log(sum3);
const familySmith = ['John', 'Jane', 'Mark'];
const familyMiller = ['Mary', 'Bob', 'Ann'];
const bigFamily = [...familySmith, 'Lily', ...familyMiller];
console.log(bigFamily);
const h = document.querySelector('h1');
const boxes = document.querySelectorAll('.box');
const all = [h, ...boxes];
Array.from(all).forEach(cur => cur.style.color = 'purple');
*/
/////////////////////////////////
// Lecture: Rest parameters
/*
//ES5
function isFullAge5() {
//console.log(arguments);
var argsArr = Array.prototype.slice.call(arguments);
argsArr.forEach(function(cur) {
console.log((2016 - cur) >= 18);
})
}
//isFullAge5(1990, 1999, 1965);
//isFullAge5(1990, 1999, 1965, 2016, 1987);
//ES6
function isFullAge6(...years) {
years.forEach(cur => console.log( (2016 - cur) >= 18));
}
isFullAge6(1990, 1999, 1965, 2016, 1987);
//ES5
function isFullAge5(limit) {
var argsArr = Array.prototype.slice.call(arguments, 1);
argsArr.forEach(function(cur) {
console.log((2016 - cur) >= limit);
})
}
//isFullAge5(16, 1990, 1999, 1965);
isFullAge5(1990, 1999, 1965, 2016, 1987);
//ES6
function isFullAge6(limit, ...years) {
years.forEach(cur => console.log( (2016 - cur) >= limit));
}
isFullAge6(16, 1990, 1999, 1965, 2016, 1987);
*/
/////////////////////////////////
// Lecture: Default parameters
/*
// ES5
function SmithPerson(firstName, yearOfBirth, lastName, nationality) {
lastName === undefined ? lastName = 'Smith' : lastName = lastName;
nationality === undefined ? nationality = 'american' : nationality = nationality;
this.firstName = firstName;
this.lastName = lastName;
this.yearOfBirth = yearOfBirth;
this.nationality = nationality;
}
//ES6
function SmithPerson(firstName, yearOfBirth, lastName = 'Smith', nationality = 'american') {
this.firstName = firstName;
this.lastName = lastName;
this.yearOfBirth = yearOfBirth;
this.nationality = nationality;
}
var john = new SmithPerson('John', 1990);
var emily = new SmithPerson('Emily', 1983, 'Diaz', 'spanish');
*/
/////////////////////////////////
// Lecture: Maps
/*
const question = new Map();
question.set('question', 'What is the official name of the latest major JavaScript version?');
question.set(1, 'ES5');
question.set(2, 'ES6');
question.set(3, 'ES2015');
question.set(4, 'ES7');
question.set('correct', 3);
question.set(true, 'Correct answer :D');
question.set(false, 'Wrong, please try again!');
console.log(question.get('question'));
//console.log(question.size);
if(question.has(4)) {
//question.delete(4);
//console.log('Answer 4 is here')
}
//question.clear();
//question.forEach((value, key) => console.log(`This is ${key}, and it's set to ${value}`));
for (let [key, value] of question.entries()) {
if (typeof(key) === 'number') {
console.log(`Answer ${key}: ${value}`);
}
}
const ans = parseInt(prompt('Write the correct answer'));
console.log(question.get(ans === question.get('correct')));
*/
/////////////////////////////////
// Lecture: Classes
/*
//ES5
var Person5 = function(name, yearOfBirth, job) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.job = job;
}
Person5.prototype.calculateAge = function() {
var age = new Date().getFullYear - this.yearOfBirth;
console.log(age);
}
var john5 = new Person5('John', 1990, 'teacher');
//ES6
class Person6 {
constructor (name, yearOfBirth, job) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.job = job;
}
calculateAge() {
var age = new Date().getFullYear - this.yearOfBirth;
console.log(age);
}
static greeting() {
console.log('Hey there!');
}
}
const john6 = new Person6('John', 1990, 'teacher');
Person6.greeting();
*/
/////////////////////////////////
// Lecture: Classes and subclasses
/*
//ES5
var Person5 = function(name, yearOfBirth, job) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.job = job;
}
Person5.prototype.calculateAge = function() {
var age = new Date().getFullYear() - this.yearOfBirth;
console.log(age);
}
var Athlete5 = function(name, yearOfBirth, job, olymicGames, medals) {
Person5.call(this, name, yearOfBirth, job);
this.olymicGames = olymicGames;
this.medals = medals;
}
Athlete5.prototype = Object.create(Person5.prototype);
Athlete5.prototype.wonMedal = function() {
this.medals++;
console.log(this.medals);
}
var johnAthlete5 = new Athlete5('John', 1990, 'swimmer', 3, 10);
johnAthlete5.calculateAge();
johnAthlete5.wonMedal();
//ES6
class Person6 {
constructor (name, yearOfBirth, job) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.job = job;
}
calculateAge() {
var age = new Date().getFullYear() - this.yearOfBirth;
console.log(age);
}
}
class Athlete6 extends Person6 {
constructor(name, yearOfBirth, job, olympicGames, medals) {
super(name, yearOfBirth, job);
this.olympicGames = olympicGames;
this.medals = medals;
}
wonMedal() {
this.medals++;
console.log(this.medals);
}
}
const johnAthlete6 = new Athlete6('John', 1990, 'swimmer', 3, 10);
johnAthlete6.wonMedal();
johnAthlete6.calculateAge();
*/
/////////////////////////////////
// CODING CHALLENGE
/*
Suppose that you're working in a small town administration, and you're in charge of two town elements:
1. Parks
2. Streets
It's a very small town, so right now there are only 3 parks and 4 streets. All parks and streets have a name and a build year.
At an end-of-year meeting, your boss wants a final report with the following:
1. Tree density of each park in the town (forumla: number of trees/park area)
2. Average age of each town's park (forumla: sum of all ages/number of parks)
3. The name of the park that has more than 1000 trees
4. Total and average length of the town's streets
5. Size classification of all streets: tiny/small/normal/big/huge. If the size is unknown, the default is normal
All the report data should be printed to the console.
HINT: Use some of the ES6 features: classes, subclasses, template strings, default parameters, maps, arrow functions, destructuring, etc.
*/
class Element {
constructor(name, buildYear) {
this.name = name;
this.buildYear = buildYear;
}
}
class Park extends Element {
constructor(name, buildYear, area, numTrees) {
super(name, buildYear);
this.area = area; //km2
this.numTrees = numTrees;
}
treeDensity() {
const density = this.numTrees / this.area;
console.log(`${this.name} has a tree density of ${density} trees per square km.`);
}
}
class Street extends Element {
constructor(name, buildYear, length, size = 3) {
super(name, buildYear);
this.length = length;
this.size = size;
}
classifyStreet () {
const classification = new Map();
classification.set(1, 'tiny');
classification.set(2, 'small');
classification.set(3, 'normal');
classification.set(4, 'big');
classification.set(5, 'huge');
console.log(`${this.name}, build in ${this.buildYear}, is a ${classification.get(this.size)} street.`);
}
}
const allParks = [new Park('Green Park', 1987, 0.2, 215),
new Park('National Park', 1894, 2.9, 3541),
new Park('Oak Park', 1953, 0.4, 949)];
const allStreets = [new Street('Ocean Avenue', 1999, 1.1, 4),
new Street('Evergreen Street', 2008, 2.7, 2),
new Street('4th Street', 2015, 0.8),
new Street('Sunset Boulevard', 1982, 2.5, 5)];
function calc(arr) {
const sum = arr.reduce((prev, cur, index) => prev + cur, 0);
return [sum, sum / arr.length];
}
function reportParks(p) {
console.log('-----PARKS REPORT-----');
// Density
p.forEach(el => el.treeDensity());
// Average age
const ages = p.map(el => new Date().getFullYear() - el.buildYear);
const [totalAge, avgAge] = calc(ages);
console.log(`Our ${p.length} parks have an average of ${avgAge} years.`);
// Which park has more than 1000 trees
const i = p.map(el => el.numTrees).findIndex(el => el >= 1000);
console.log(`${p[i].name} has more than 1000 trees.`);
}
function reportStreets(s) {
console.log('-----STREETS REPORT-----');
//Total and average length of the town's streets
const [totalLength, avgLength] = calc(s.map(el => el.length));
console.log(`Our ${s.length} streets have a total length of ${totalLength} km, with an average of ${avgLength} km.`);
// CLassify sizes
s.forEach(el => el.classifyStreet());
}
reportParks(allParks);
reportStreets(allStreets);