-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanswer.js
More file actions
474 lines (379 loc) · 11.2 KB
/
answer.js
File metadata and controls
474 lines (379 loc) · 11.2 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
// problem 1: Write a function that takes two numbers as arguments and returns their sum.
// es5 version
function add(num1, num2) {
return num1 + num2;
}
// es6 version
const add = (num1, num2) => num1 + num2;
// problem 2: Write a function that takes an array of numbers as an argument and returns the largest number in the array.
// es5 version
function findLargest(arr) {
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// es6 version
const findLargest = (arr) => Math.max(...arr);
// problem 3: Write a function that takes a string as an argument and returns the string in reverse order
// es5 version
function reverseString(str) {
let reversed = "";
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
// es6 version
const reverseString = (str) => str.split("").reverse().join("");
// problem 4: Write a function that takes a number as an argument and returns the factorial of that number.
// es5 version
function factorial(num) {
let result = 1;
for (let i = 2; i <= num; i++) {
result *= i;
}
return result;
}
// es6 version
const factorial = (num) => {
let result = 1;
for (let i = 2; i <= num; i++) {
result *= i;
}
return result;
};
// problem 5: Write a function that takes an array of strings as an argument and returns the longest string in the array.
// es5 version
function findLongestString(arr) {
var longestString = "";
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > longestString.length) {
longestString = arr[i];
}
}
return longestString;
}
// es6 version 1 (reduce)
const findLongestString = (arr) =>
arr.reduce((a, b) => (a.length > b.length ? a : b));
// es6 version 2 (forEach)
const findLongestString2 = (arr) => {
let longestString = "";
arr.forEach((str) => {
if (str.length > longestString.length) {
longestString = str;
}
});
return longestString;
};
// problem 6: Write a function that takes an array of numbers as an argument and returns the array in reverse order.
// es5 version
function reverseArray(arr) {
var reversed = [];
for (var i = arr.length - 1; i >= 0; i--) {
reversed.push(arr[i]);
}
return reversed;
}
// es6 version 1
const reverseArray = (arr) => arr.reverse();
// es6 version 2
const reverseArray = (arr) => {
const copy = [...arr];
const reversed = [];
while (copy.length) {
reversed.push(copy.pop());
}
return reversed;
};
// Example usage:
console.log(reverseArray([1, 2, 3, 4, 5])); // Output: [5, 4, 3, 2, 1]
// problem 7: Write a function that takes an array of numbers as an argument and returns the array in sorted order.
// es5 version
function sortArray(arr) {
return arr.sort(function (a, b) {
return a - b;
});
}
// es6 version
const sortArray = (arr) => arr.sort((a, b) => a - b);
// Example usage:
console.log(sortArray([5, 2, 8, 3, 1])); // Output: [1, 2, 3, 5, 8]
// es6 es5
function sortArray(arr) {
return arr.sort(function (a, b) {
return a.number - b.number;
});
}
// Example usage:
console.log(
sortArray([
{ number: 5 },
{ number: 2 },
{ number: 8 },
{ number: 3 },
{ number: 1 },
])
); // Output: [{number: 1}, {number: 2}, {number: 3}, {number: 5}, {number: 8}]
// problem 8: Write a function that takes an array of strings as an argument and returns the array in sorted order.
// es5 version
function sortArray(arr) {
return arr.sort(function (a, b) {
return a.localeCompare(b);
});
}
// es6 version
const sortArray = (arr) => arr.sort((a, b) => a.localeCompare(b));
// Example usage:
console.log(sortArray(["cat", "dog", "apple", "zebra", "banana"])); // Output: ['apple', 'banana', 'cat', 'dog', 'zebra']
// problem 9: Write a function that takes an array of numbers as an argument and returns the sum of all the numbers in the array.
// es5 version
function sumArray(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
// reduce version
function sumArray(arr) {
return arr.reduce(function (acc, cur) {
return acc + cur;
}, 0);
}
// es6 version
const sumArray = (arr) => {
let sum = 0;
for (let num of arr) {
sum += num;
}
return sum;
};
// es6 version 2
const sumArray = (arr) => arr.reduce((acc, cur) => acc + cur, 0);
// Example usage:
console.log(sumArray([1, 2, 3, 4, 5])); // Output: 15
console.log(sumArray([-1, 2, -3, 4, -5])); // Output: -3
/**
* problem 10:
* Write a function that takes an array of numbers as an argument and returns an object with the following properties:
* sum: the sum of all the numbers in the array
* average: the average of all the numbers in the array
* isEven: true if all the numbers in the array are even, false otherwise
* */
// es5 version
function analyzeNumbers(arr) {
var sum = arr.reduce(function (acc, cur) {
return acc + cur;
}, 0);
var average = sum / arr.length;
var isEven = arr.every(function (num) {
return num % 2 === 0;
});
return { sum: sum, average: average, isEven: isEven };
}
// es6 version
const analyzeNumbers = (arr) => {
const sum = arr.reduce((acc, cur) => acc + cur, 0);
const average = sum / arr.length;
const isEven = arr.every((num) => num % 2 === 0);
return { sum, average, isEven };
};
// Example usage:
console.log(analyzeNumbers([2, 4, 6, 8])); // Output: { sum: 20, average: 5, isEven: true }
console.log(analyzeNumbers([1, 2, 3, 4, 5])); // Output: { sum: 15, average: 3, isEven: false }
/** problem 11:
* Create a class Person that has the following properties:
* name (string)
* age (number)
* gender (string)
* It should have a method getDetails that returns a string with the person's name, age, and gender.
*/
// es5 version
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
Person.prototype.getDetails = function () {
return (
"Name: " + this.name + ", Age: " + this.age + ", Gender: " + this.gender
);
};
// es6 version
class Person {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
getDetails() {
return `Name: ${this.name}, Age: ${this.age}, Gender: ${this.gender}`;
}
}
// Example usage:
const person = new Person("John", 30, "male");
console.log(person.getDetails()); // Output: "Name: John, Age: 30, Gender: male"
// problem 12: Write a function that takes an array of numbers as an argument and returns a new array with only the even numbers
// es5 version
function getEvenNumbers(arr) {
var evenNumbers = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
evenNumbers.push(arr[i]);
}
}
return evenNumbers;
}
// es6 version
const getEvenNumbers = (arr) => arr.filter((num) => num % 2 === 0);
// Example usage:
console.log(getEvenNumbers([1, 2, 3, 4, 5, 6])); // Output: [2, 4, 6]
console.log(getEvenNumbers([-2, -1, 0, 1, 2])); // Output: [-2, 0, 2]
/** problem 13: Create a class Student that extends the Person class. It should have the following properties:
name (string)
age (number) */
// es5 version
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function () {
console.log(
"Hello, my name is " + this.name + " and I'm " + this.age + " years old."
);
};
function Student(name, age, studentId, major) {
Person.call(this, name, age);
this.studentId = studentId;
this.major = major;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.showStudentInfo = function () {
console.log(
"I'm " +
this.name +
", a " +
this.major +
" major student with student ID " +
this.studentId +
"."
);
};
// es6 version
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(
`Hello, my name is ${this.name} and I'm ${this.age} years old.`
);
}
}
class Student extends Person {
constructor(name, age, studentId, major) {
super(name, age);
this.studentId = studentId;
this.major = major;
}
showStudentInfo() {
console.log(
`I'm ${this.name}, a ${this.major} major student with student ID ${this.studentId}.`
);
}
}
// Example usage:
const john = new Student("John", 20, "1234", "Computer Science");
john.sayHello(); // Output: Hello, my name is John and I'm 20 years old.
john.showStudentInfo(); // Output: I'm John, a Computer Science major student with student ID 1234.
// problem 14: Write a function that takes an array of strings as an argument and returns a new array with only the strings that are longer than 5 characters
// es5 version
function filterLongStrings(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > 5) {
result.push(arr[i]);
}
}
return result;
}
// es6 version
const filterLongStrings = (arr) => arr.filter((str) => str.length > 5);
// Example usage:
const words = ["apple", "banana", "cherry", "date", "elderberry", "fig"];
const longWords = filterLongStrings(words);
console.log(longWords); // Output: ["banana", "cherry", "elderberry"]
// problem 15: Write a function that takes an array of numbers as an argument and returns a new array with only the numbers that are divisible by 5
// es5 version
function filterDivisibleByFive(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] % 5 === 0) {
result.push(arr[i]);
}
}
return result;
}
// es6 version
const filterDivisibleByFive = (arr) => arr.filter((num) => num % 5 === 0);
// Example usage:
const numbers = [1, 5, 10, 13, 15, 20, 25];
const divisibleByFive = filterDivisibleByFive(numbers);
console.log(divisibleByFive); // Output: [5, 10, 15, 20, 25]
// problem 16: How can you sort an array of objects by a specific property in JavaScript?
const arr = [
{ name: "John", age: 25 },
{ name: "Jane", age: 30 },
{ name: "Bob", age: 20 },
];
// es5 version
function compareByAge(a, b) {
// Compare the age property of the two objects
if (a.age < b.age) {
return -1;
}
if (a.age > b.age) {
return 1;
}
return 0;
}
arr.sort(compareByAge);
// es6 version
const compareByAge = (a, b) => a.age - b.age;
arr.sort(compareByAge);
console.log(arr);
// Output: [{ name: 'Bob', age: 20 }, { name: 'John', age: 25 }, { name: 'Jane', age: 30 }]
// problem 17: How can you convert a string to title case (capitalize the first letter of each word) using JavaScript?
// es5 version
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
// es6 version
const toTitleCase = (str) =>
str.replace(
/\w\S*/g,
(txt) => `${txt.charAt(0).toUpperCase()}${txt.substr(1).toLowerCase()}`
);
const input = "the quick brown fox";
const output = toTitleCase(input);
console.log(output); // Output: "The Quick Brown Fox"
// problem 18: How can you check if a string contains a substring in JavaScript?
// es5 version
const str = "The quick brown fox jumps over the lazy dog";
if (str.includes("fox")) {
console.log('String contains "fox"');
} else {
console.log('String does not contain "fox"');
}
// ternary operator
const hasFox = str.includes("fox") ? true : false;
console.log(`String ${hasFox ? "contains" : "does not contain"} "fox"`);