File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11// ==== Challenge 1: Write your own closure ====
22// Write a simple closure of your own creation. Keep it simple!
3-
3+ for ( var i = 0 ; i < 5 ; i ++ ) {
4+ ( function ( ) {
5+ var savingI = i ;
6+
7+ //timer callback executes after loop
8+ setTimeout ( function ( ) {
9+ console . log ( `number from timer callback ${ savingI } ` ) ;
10+ } , 1000 ) ;
11+ } ) ( ) ;
12+ }
413
514// ==== Challenge 2: Create a counter function ====
615const counter = ( ) => {
716 // Return a function that when invoked increments and returns a counter variable.
17+ let value = 0 ;
18+
19+ return function ( ) {
20+ console . log ( value ++ ) ;
21+ }
822} ;
923// Example usage: const newCounter = counter();
1024// newCounter(); // 1
1125// newCounter(); // 2
26+ const newCounter = counter ( ) ;
27+ newCounter ( ) ;
28+ newCounter ( ) ;
1229
1330/* STRETCH PROBLEM, Do not attempt until you have completed all previous tasks for today's project files */
1431
1532// ==== Challenge 3: Create a counter function with an object that can increment and decrement ====
1633const counterFactory = ( ) => {
34+
35+ let value = 0 ;
36+
1737 // Return an object that has two methods called `increment` and `decrement`.
1838 // `increment` should increment a counter variable in closure scope and return it.
1939 // `decrement` should decrement the counter variable and return it.
40+
41+ return {
42+ increment : function ( ) {
43+ console . log ( value ++ ) ;
44+ } ,
45+ decrement : function ( ) {
46+ console . log ( value -- ) ;
47+ }
48+ }
2049} ;
50+
51+ console . log ( "\n From counter2: \n" ) ;
52+ const newCounter2 = counterFactory ( ) ;
53+ for ( let i = 0 ; i < 20 ; i ++ ) {
54+ if ( i % 3 === 0 ) {
55+ newCounter2 . decrement ( ) ;
56+ } else {
57+ newCounter2 . increment ( ) ;
58+ }
59+ }
You can’t perform that action at this time.
0 commit comments