-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiffy.js
106 lines (79 loc) · 1.81 KB
/
iffy.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
// IIFE - immediately invoke function expression
// syntax
// way-1
(()=>{
})();
// way-2
(function(){
})();
// way-3
(function myIIFE(){
})();
// Reason - 1) Does not pollute the global object namespace.
// We can use this for isolation
const x = "whatever";
const helloworld = () => "Hello World!";
(()=> {
const x = "iife whatever";
const helloworld = () => "Hello IIFE!";
console.log(x);
console.log(helloworld());
})();
// Reason - 2) Private variables and Methods from Closure
const increment = (()=> {
let counter = 0;
console.log(counter);
const credits = (num) => console.log(`I have ${num} credits`);
return () => {
counter++;
credits(counter);
}
})();
// increment();
// increment();
// Reason - 3)
/*
The module pattern in JavaScript is a design pattern that helps you to encapsulate
and manage the functionality of your code by creating private and public elements.
It provides a way to organize code and manage the scope of variables and functions,
making it easier to avoid conflicts and create reusable code.
*/
// Module Pattern
const Score = (()=>{
let counter = 0;
return {
increment:()=>{counter++;},
getIncrement:()=>{
return counter;
},
reset: ()=>{
counter = 0;
}
}
}
)();
Score.increment();
console.log(Score.getIncrement())
Score.increment();
console.log(Score.getIncrement())
Score.increment();
console.log(Score.getIncrement())
// Reveling Pattern
const Game = (()=>{
let counter = 0;
const increment = ()=>{counter++;};
const getIncrement = ()=>{ return counter }
const reset = ()=> { counter = 0; }
return {
increment,
getIncrement,
reset
}
}
)();
Game.increment();
console.log(Game.getIncrement())
Game.increment();
console.log(Game.getIncrement())
Game.increment();
console.log(Game.getIncrement())