Skip to content

Commit 3e17be3

Browse files
committed
completed closures
1 parent dab4373 commit 3e17be3

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

‎assignments/closure.js‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,61 @@
11
// ==== Challenge 1: Write your own closure ====
22
// Write a simple closure of your own creation. Keep it simple!
3+
function multiply(x){
4+
return function (y) {
5+
return x * y;
6+
};
7+
}
38

9+
let multiply2 = multiply(2);
10+
// console.log(multiply2(4)); // returns 8.
411

512
// ==== Challenge 2: Create a counter function ====
613
const counter = () => {
14+
let y = 0;
715
// Return a function that when invoked increments and returns a counter variable.
16+
return function() {
17+
return y++;
18+
}
819
};
20+
let addBy1 = counter();
21+
console.log(addBy1());
22+
console.log(addBy1());
923
// Example usage: const newCounter = counter();
1024
// newCounter(); // 1
1125
// newCounter(); // 2
1226

1327

1428
// ==== Challenge 3: Create a counter function with an object that can increment and decrement ====
1529
const counterFactory = () => {
30+
let x = 0;
1631
// Return an object that has two methods called `increment` and `decrement`.
1732
// `increment` should increment a counter variable in closure scope and return it.
1833
// `decrement` should decrement the counter variable and return it.
34+
return {
35+
increment() {
36+
return ++x;
37+
},
38+
decrement() {
39+
return --x;
40+
}
41+
}
1942
};
43+
44+
let count = 8;
45+
let test = counterFactory() ;
46+
// console.log(test.increment());
47+
// console.log(test.increment());
48+
// console.log(test.increment());
49+
// console.log(test.increment());
50+
// console.log(test.increment());
51+
// console.log(test.increment());
52+
// console.log(test.increment());
53+
// console.log(test.decrement());
54+
// console.log(test.decrement());
55+
// console.log(test.decrement());
56+
// console.log(test.decrement());
57+
58+
let test2 = counterFactory();
59+
// console.log(test2.increment());
60+
// will allow you to create multiple variables storing the information separately.
61+

0 commit comments

Comments
 (0)