|
1 | 1 | // ==== Challenge 1: Write your own closure ==== |
2 | 2 | // 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 | +} |
3 | 8 |
|
| 9 | +let multiply2 = multiply(2); |
| 10 | +// console.log(multiply2(4)); // returns 8. |
4 | 11 |
|
5 | 12 | // ==== Challenge 2: Create a counter function ==== |
6 | 13 | const counter = () => { |
| 14 | + let y = 0; |
7 | 15 | // Return a function that when invoked increments and returns a counter variable. |
| 16 | + return function() { |
| 17 | + return y++; |
| 18 | + } |
8 | 19 | }; |
| 20 | +let addBy1 = counter(); |
| 21 | +console.log(addBy1()); |
| 22 | +console.log(addBy1()); |
9 | 23 | // Example usage: const newCounter = counter(); |
10 | 24 | // newCounter(); // 1 |
11 | 25 | // newCounter(); // 2 |
12 | 26 |
|
13 | 27 |
|
14 | 28 | // ==== Challenge 3: Create a counter function with an object that can increment and decrement ==== |
15 | 29 | const counterFactory = () => { |
| 30 | + let x = 0; |
16 | 31 | // Return an object that has two methods called `increment` and `decrement`. |
17 | 32 | // `increment` should increment a counter variable in closure scope and return it. |
18 | 33 | // `decrement` should decrement the counter variable and return it. |
| 34 | + return { |
| 35 | + increment() { |
| 36 | + return ++x; |
| 37 | + }, |
| 38 | + decrement() { |
| 39 | + return --x; |
| 40 | + } |
| 41 | + } |
19 | 42 | }; |
| 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