Skip to content

Commit fe2b53f

Browse files
committed
finished callbacks
1 parent db6af5e commit fe2b53f

1 file changed

Lines changed: 40 additions & 1 deletion

File tree

assignments/closure.js

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,59 @@
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 ====
615
const 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 ====
1633
const 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+
}

0 commit comments

Comments
 (0)