-
Notifications
You must be signed in to change notification settings - Fork 0
/
FCC-js-tutorial-part-02.js
275 lines (238 loc) · 7.01 KB
/
FCC-js-tutorial-part-02.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
//ES6 Modules
// *2.1 Compare Scopes of the var and let Keywords
function checkScope() {
'use strict';
let i = 'function scope';
if (true) {
let i = 'block scope';
console.log('Block scope i is: ', i);
}
console.log('Function scope i is: ', i);
return i;
}
//* 2.2 Mutate an Array Declared with const
'use strict';
const s = [5, 7, 2];
// change code below this line
s[0] = 2; s[1] = 5; s[2] = 7;
// change code above this line
// Test your code
console.log(s);
//* 2.3 Prevent Object Mutation
function freezeObj() {
'use strict';
const MATH_CONSTANTS = {
PI: 3.14
};
Object.freeze(MATH_CONSTANTS);
try {
MATH_CONSTANTS.PI = 99;
} catch (ex) {
console.log(ex);
}
return MATH_CONSTANTS.PI;
}
const PI = freezeObj();
//* 2.4 Use Arrow Functions to Write Concise Anonymous Functions
const magic = () => {
"use strict";
return new Date();
};
//* 2.5 Write Arrow Functions with Parameters
const myConcat = (arr1, arr2) => {
"use strict";
return arr1.concat(arr2);
};
console.log(myConcat([1, 2], [3, 4, 5]));
//* 2.6 Set Default Parameters for Your Functions
function increment(number, value = 1) {
return number + value;
}
console.log(increment(5, 2)); // returns 7
console.log(increment(5)); // returns NaN
//* 2.7 Use the Rest Parameter with Function Parameters
const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
}
//* 2.8 Use the Spread Operator to Evaluate Arrays In-Place
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
arr2 = [...arr1];
console.log(arr2);
//* 2.9 Use Destructuring Assignment to Extract Values from Objects
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
const { today, tomorrow } = HIGH_TEMPERATURES;
//* 2.10 Use Destructuring Assignment to Assign Variables from Objects
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
const { today: highToday, tomorrow: highTomorrow } = HIGH_TEMPERATURES;
//* 2.11 Use Destructuring Assignment to Assign Variables from Nested Objects
const LOCAL_FORECAST = {
yesterday: { low: 61, high: 75 },
today: { low: 64, high: 77 },
tomorrow: { low: 68, high: 80 }
};
const { today: { low: lowToday, high: highToday } } = LOCAL_FORECAST;
//* 2.12 Use Destructuring Assignment to Assign Variables from Arrays
let a = 8, b = 6;
// Only change code below this line
[a, b] = [b, a];
//*2.13 Destructuring via rest elements
function removeFirstTwo(list) {
// Only change code below this line
const [, , ...shorterList] = list; // Change this line
// Only change code above this line
return shorterList;
}
const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const sourceWithoutFirstTwo = removeFirstTwo(source);
//* 2.14 Use Destructuring Assignment to Pass an Object as a Function's Parameters
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};
const half = ({ max, min }) => (max + min) / 2.0;
//* 2.15 Create Strings using Template Literals
const result = {
success: ["max-length", "no-amd", "prefer-arrow-functions"],
failure: ["no-var", "var-on-top", "linebreak"],
skipped: ["no-extra-semi", "no-dup-keys"]
};
function makeList(arr) {
"use strict";
// change code below this line
const failureItems = [];
for (let i = 0; i < arr.length; i++) {
failureItems.push(`<li class="text-warning">${arr[i]}</li>`);
}
// change code above this line
return failureItems;
}
const failuresList = makeList(result.failure);
//* 2.16 Write Concise Object Literal Declarations Using Object Property Shorthand
const createPerson = (name, age, gender) => {
"use strict";
return {
name,
age,
gender
};
};
//* 2.17 Write Concise Declarative Functions with ES6
const bicycle = {
gear: 2,
setGear(newGear) {
this.gear = newGear;
}
};
bicycle.setGear(3);
console.log(bicycle.gear);
//* 2.18 Use class Syntax to Define a Constructor Function
class Vegetable {
constructor(name) {
this.name = name;
}
}
const carrot = new Vegetable('carrot');
console.log(carrot.name); // Should display 'carrot'
//* 2.19 Use getters and setters to Control Access to an Object
class Thermostat {
constructor(fahrenheit) {
this.fahrenheit = fahrenheit;
}
get temperature() {
return (5 / 9) * (this.fahrenheit - 32);
}
set temperature(celsius) {
this.fahrenheit = (celsius * 9.0) / 5 + 32;
}
}
const thermos = new Thermostat(76); // Setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in Celsius
thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius
//* 2.20 Create a Module Script
<html>
<body>
{/* <!-- Only change code below this line --> */}
<script type="module" src="index.js"></script>
{/* <!-- Only change code above this line --> */}
</body>
</html>
//* 2.21 Use export to Share a Code Block
const uppercaseString = (string) => {
return string.toUpperCase();
}
const lowercaseString = (string) => {
return string.toLowerCase()
}
export { uppercaseString, lowercaseString };
//* 2.22 Reuse JavaScript Code Using import
import { uppercaseString, lowercaseString } from './string_functions.js';
uppercaseString("hello");
lowercaseString("WORLD!");
//* 2.23 Use * to Import Everything from a File
import * as stringFunctions from "./string_functions.js";
stringFunctions.uppercaseString("hello");
stringFunctions.lowercaseString("WORLD!");
//* 2.24 Create an Export Fallback with export default
export default function subtract(x, y) {
return x - y;
}
//* 2.25 Import a Default Export
import subtract from "./math_functions.js"
// Only change code above this line
subtract(7, 4);
//* 2.26 Create a JavaScript Promise
const makeServerRequest = new Promise((resolve, reject) => {
})
//* 2.27 Complete a Promise with resolve and reject
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer represents a response from a server
let responseFromServer;
if (responseFromServer) {
resolve("We got the data")
} else {
reject("Data not received")
}
});
//* 2.28 Handle a Fulfilled Promise with then
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer represents a response from a server
let responseFromServer;
if (responseFromServer) {
resolve("We got the data")
} else {
reject("Data not received")
}
makeServerRequest.then(result => {
console.log(result);
})
});
//* 2.29 Handle a Rejected Promise with catch
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer represents a response from a server
let responseFromServer;
if (responseFromServer) {
resolve("We got the data")
} else {
reject("Data not received")
}
makeServerRequest.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
})
});