-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_15.js
250 lines (176 loc) · 5.38 KB
/
day_15.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
/* Day 15: Closures */
/* Activity 1: Understanding Clousers */
// Task 1 : write a function that returns another function , where inner function access the variable from outer functions scope. call inner functions and log the result
function animal() {
let numOfLegs = 2;
function dog() {
numOfLegs = 4;
console.log(`My dog have ${numOfLegs} legs.`)
}
dog();
}
animal();
// Task 2: Create a closure that maintains a private counter. implement functions to increament and get the current value of the counter
function counter() {
let currCounter = 0;
return function incCounter() {
console.log(`Counter increased to ${++currCounter}.`);
}
}
const count = counter();
count();
/* Activity 2: Practical Closures */
// Task 3: Write a function that generates unique IDs. Use a closure to keep track of the last generated ID and increment it with each call.
function uniqueIDs() {
let id = 1000;
return function generateNextID() {
return ++id;
}
}
const currID = uniqueIDs();
for (let i = 0; i < 5; i++) {
console.log(`Curr ID is ${currID()}.`);
};
// Task 4: create a closure that captures user name, return a greet function which greets the user by its name
function greetUser(user) {
this.user = user;
return function message() {
console.log(`Hi ${user}, nice to meet you.`)
}
// message();
}
const greet = greetUser("Prince");
greet();
/* Activity 3: Closures in loops */
// Task 5: write a loop that creates an array of functions. each function should log its index when called. use closure to ensure that each function call the correct index.
function createFunction() {
let functions = [];
function createFunc(index) {
return function() {
console.log(`Index of the function is - ${index}.`);
};
}
for(let i = 0; i<3; i++) {
functions[i] = createFunc(i);
}
return functions;
}
const functionArray = createFunction();
for (let i = 0; i < functionArray.length; i++) {
functionArray[i]();
}
/* Activity 4: Module Pattern */
//Task 6: Use closures to create a simple module for managing a collection of items, implement methods to add, remove and list items.
// const itemModule = (() => {
// let items = [];
// function add(item) {
// items.push(item);
// }
// function remove(item) {
// items = items.filter(function(i) {
// return i !== item;
// })
// }
// function listItems() {
// return items;
// }
// return {add, remove, listItems};
// })();
// itemModule.add(1);
// itemModule.add(2);
// itemModule.add(3);
// itemModule.add(4);
// console.log(itemModule.listItems());
// itemModule.remove(2);
// console.log(itemModule.listItems());
/* making a function */
function itemModule() {
let items = [];
function add(item) {
items.push(item);
}
function remove(item) {
items = items.filter(function(i) {
return i !== item;
})
}
function listItems() {
return items;
}
return {add, remove, listItems};
};
// export {itemModule};
const ans = itemModule();
ans.add(1);
ans.add(2);
ans.add(3);
ans.add(4);
console.log(ans.listItems());
ans.remove(2);
console.log(ans.listItems());
/* Activity 5: Memoization */
// Task 7: Write a function that memoizes the result of another function. Use a closure to store the result of the previous computations.
function memoize(fn) {
const cache = {};
return function(num) {
const key = JSON.stringify(num);
if(cache[key]) {
return cache[key];
} else {
const result = fn(num);
cache[key] = result;
return result
}
};
}
function slowFunction(num) {
return num * 2;
}
const memoizedSlowFunction = memoize(slowFunction);
console.log(memoizedSlowFunction(5)); // Computed and cached
console.log(memoizedSlowFunction(5)); // Retrieved from cache
console.log(memoizedSlowFunction(10)); // Computed and cached
console.log(memoizedSlowFunction(10)); // Retrieved from cache
// Task 8: create a memoized version of a function which calculates the factorial of a number
function memoizeNew(fn) {
const cache = {};
return function(num) {
const key = JSON.stringify(num);
if(cache[key]) {
return cache[key];
}
else {
const result = fn(num);
cache[key] = result;
return result;
}
}
}
function factorial(num) {
if(num <= 1) {
return 1;
}
return num * factorial(num-1);
}
const memoizeFactorial = memoizeNew(factorial);
console.log(factorialMemo(6));
console.log(factorialMemo(9));
// In below logic we store the ans for any previous calls in cache memory and then use it to find factorial for next call.
let cache = {};
function factorialMemo(n) {
if(n == 0) {
return 1;
}
if(Object.keys(cache).length === 0) {
const result = n * factorialMemo(n-1);
cache[n] = result;
}
if(cache[n] !== undefined) {
return cache[n];
}
cache[n] = n * factorialMemo(n-1);
return cache[n];
}
console.log(memoizeFactorial(6)); // calculate for factorial of 6
console.log(memoizeFactorial(9)); // cache factorial of 6 and use it for factorial of 9
console.log(memoizeFactorial(12)); //cache factorial of 9 and use it for factorial of 12