-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04_Function.js
327 lines (279 loc) · 11 KB
/
04_Function.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
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
/*
Description:
Function
Modifications:
---------------------------------------------------------------------------------------
Date Vers. Comment Name
---------------------------------------------------------------------------------------
21.07.13 01.00 Created Siddiqui
07.11.23 02.00 Updated Siddiqui
---------------------------------------------------------------------------------------
*/
'use strict';
// ==========================================================================================================
// Hoisting
// ==========================================================================================================
// Using a variable before it is declared
// Only when var is used, NOT with let/const
// Only declaration is hoisted, not the initialization value
func = () => {
console.log(child_var); // Hoisted value
var child_var;
child_var = 55;
console.log(child_var); // Initialized value
}
func();
// ==========================================================================================================
// Self Invocation Function
// ==========================================================================================================
// To avoid polluting global namespace
const result = (() => {
let a = 2, b = 3;
return a + b;
})();
// ==========================================================================================================
// Passing context
// ==========================================================================================================
const outer_function = (self) => {
console.log(self.prop);
}
const parent = {
prop: "Hello",
inner_function() {
let self = this;
outer_function(self);
}
};
parent.inner_function();
// ==========================================================================================================
// Argument Identifier
// ==========================================================================================================
// Note: Arrow functions have no argument identifier
function some_function() {
console.log(arguments[1]);
console.log(arguments.length);
}
some_function(1, 2, 3);
// ==========================================================================================================
// Procedure - Function without return value
// ==========================================================================================================
const procedure = () => {
// Do some task
// No return value
}
// ==========================================================================================================
// Arrow Functions
// ==========================================================================================================
// Arrow functions can't be called with new
// ----------------------------------------------------
// Default return
// ----------------------------------------------------
var getter = (a, b) => a * b;
console.log(getter(1, 2));
// ----------------------------------------------------
// Object return
// ----------------------------------------------------
getter = (a, b) => ({ 'x': a, 'y': b }); // Note () around object
getter = (a, b) => {
return { 'x': a, 'y': b }
}
console.log(getter(1, 2));
// ----------------------------------------------------
// No separate internal this
// ----------------------------------------------------
// Arrow functions don't define their own this
let objects = {
students: [{ name: 'Aisha', class: 2 }, { name: 'Amna', class: 3 }],
school: 'RoseLand Public School',
printer() {
this.students.forEach(student => {
console.log(`School: ${this.school}`); // *this* is from outer scope
console.log(`Student: ${student.name}`);
});
}
}
objects.printer();
// ==========================================================================================================
// Timeout and Interval
// ==========================================================================================================
// ----------------------------------------------------
// Start After T seconds
// ----------------------------------------------------
var func = (a, t) => {
setTimeout(() => { console.log(a) }, t);
}
func(1, 1000);
// ----------------------------------------------------
// End after T seconds
// ----------------------------------------------------
func = (a, t) => {
const id = setInterval(() => { console.log(a) });
setTimeout(() => { clearInterval(id) }, t);
}
func(1, 1000);
// ----------------------------------------------------
// Repeat Every T seconds for N Times
// ----------------------------------------------------
func = (a, t, n) => {
let counter = 0;
// Set Repeater
const id = setInterval(() => {
counter += 1; console.log(a);
// Reset Repeater
if (counter >= n) { clearInterval(id); }
}, t);
}
func(3, 1000, 10);
// ----------------------------------------------------
// Note
// ----------------------------------------------------
// If a function takes longer than setInterval, interpreter waits until function is complete
// ==========================================================================================================
// Spread and Rest Parameters
// ==========================================================================================================
func = (a, b, ...other) => { // Rest
console.log(a);
console.log(b);
console.log(other); // Array
console.log(...other); // Spread
};
func(1, 2, 3, 4, 5, 6);
let multiplier = (...args) => {
return args.reduce((a, b) => a * b);
};
// ==========================================================================================================
// Recursion
// ==========================================================================================================
// https://javascript.info/recursion
// ==========================================================================================================
// Decorator
// ==========================================================================================================
// ----------------------------------------------------
// Timer Decorator
// ----------------------------------------------------
const timer = (func) => {
return (...args) => { // return wrapper function
let t1 = Date.now(); // Start time
let data = func(...args); // Call decorated function
let t2 = Date.now(); // End time
console.log(`${t2 - t1}ms`);
return data; // Return result of decorated function
}
};
// ----------------------------------------------------
// Repeater Decorator
// ----------------------------------------------------
const n_times = (n, func) => {
return (...args) => {
let counter = 0;
const id = setInterval(() => {
// Run the decorated function
let data = func(...args);
console.log(`Output: ${data}`);
// Stop the Interval
counter += 1;
if (counter >= n) { clearInterval(id); }
}, 1000);
};
};
multiplier = n_times(10, multiplier);
multiplier(1, 2, 3);
// ==========================================================================================================
// Call vs Apply vs Rest
// ==========================================================================================================
// - Call:
// - It takes N arguments
// - First argument binds to this
// - Other arguments as parameter (spread)
// - Apply:
// - It takes only one argument (list). List binds to this
let data1 = { x: 1, y: 2, z: 3 };
let data2 = [1, 2, 3];
let data3 = 99
// ----------------------------------------------------
// Apply (A = Array) - Deprecated
// ----------------------------------------------------
function apply_fn() {
console.log(this[0]); // data 1
console.log(this[1]); // data 2
console.log(this[2]) // data 3
}
// ----------------------------------------------------
// Call (C = Comma) - Deprecated
// ----------------------------------------------------
function call_fn(...args) {
console.log(this); // data 1
console.log(args[0]); // data 2
console.log(args[1]); // data 3
}
// ----------------------------------------------------
// Arrow Function (Spread) - Recommended
// ----------------------------------------------------
const arrow_fn = (...args) => {
console.log(args[0]); // data 1
console.log(args[1]); // data 2
console.log(args[2]); // data 3
};
// ----------------------------------------------------
// Function (Spread)
// ----------------------------------------------------
function func(...args) {
console.log(args[0]); // data 1
console.log(args[1]); // data 2
console.log(args[2]); // data 3
}
apply_fn.apply([data1, data2, data3]);
call_fn.call(data1, data2, data3);
arrow_fn(data1, data2, data3);
func(data1, data2, data3);
// ==========================================================================================================
// Currying / Partial Functions
// ==========================================================================================================
// ----------------------------------------------------
// Function
// ----------------------------------------------------
function print_function(a, b, c) { console.log(a, b, c); }
print_function(1, 2, 3);
// ----------------------------------------------------
// Currying
// ----------------------------------------------------
// Function(a,b,c) => Function(a)(b)(c)
function curry(f) {
return function (a) {
return function (b) {
return function (c) {
return f(a, b, c);
}
}
}
}
let print_curry = curry(print_function);
print_curry(1)(2)(3);
// ----------------------------------------------------
// Partial Function
// ----------------------------------------------------
// Method-1
let print_partial = curry(print_function)(1)(2);
print_partial(3);
// Method-2
function print_partial(a, c) {
return print_function(a, 2, c);
}
print_partial(1, 3);
// ==========================================================================================================
// Closure
// ==========================================================================================================
// - Definition: Nested function has access to parent function scope even after parent function is terminated
// - Reason: Function gets the value where they are defined not where they are invoked
// - Benefit: It is a data hiding mechanism
// - Note: A parent function depending upon nested function value is not a closure
function parent(outer_value) {
function child(inner_value) {
return outer_value + inner_value;
}
return child;
}
const a = parent(1);
const b = parent(2);
console.log(a(2));
console.log(b(2));