-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopQnA4Interview.js
71 lines (59 loc) · 1.81 KB
/
TopQnA4Interview.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
// ================Map, Filter and forEach Concept===============================
(function main() {
let arr = [1, 2, 3, 4, 5, 6, 7];
const result = arr.map((num) => (num % 2 === 0 ? num : null))
.filter((num) => num !== null);
result.forEach((num) => {
console.log(num);
return;
})
}());
// ================Deep and Shallow Copy Concept===============================
/* In summary:
- Shallow copy: New reference, same memory location, changes affect original.
- Deep copy: New object/array, new memory location, changes don't affect original.
*/
(function main() {
let orig = [1,2,3];
// let shallowCopy = orig;
// shallowCopy.push(4);
let deepCopy = [...orig];
deepCopy.push(4);
console.log('Original Values changes in Shallow Copy: ', orig );
console.log('Original Values does not change in Deep Copy: ', deepCopy);
}());
// ================Closure Concept===============================
function outer() {
let x = 5;
function inner(y) {
let sum = x + y;
return sum;
}
x = 3;
return inner;
}
let ans = outer(); // 'outer' is called, which returns the 'inner' function. 'ans' now holds the 'inner' function
console.log(ans(2)); // 'ans' (which is the 'inner' function) is called with 'y' as 2, so it returns 5 + 2 = 7
// ================Memoize Concept===============================
function square(n){
return n*n;
}
function memoize(fn){
return function(...args){
let cache = {};
let n = args[0];
if(n in cache){
return cache[n];
}else{
let result = fn(n);
return fn(n);
}
}
}
console.time();
let res = memoize(square);
console.log(res(5));
console.timeEnd();
console.time();
console.log(res(5));
console.timeEnd();