|
2 | 2 | // Write a simple closure of your own creation. Keep it simple! |
3 | 3 |
|
4 | 4 |
|
| 5 | +function giveFullName() { |
| 6 | + let fullName = ""; |
| 7 | + |
| 8 | + const combineTitleFirstLast = function(title, firstName, lastName) { |
| 9 | + fullName = `${title} ${firstName} ${lastName}`; |
| 10 | + return fullName; |
| 11 | + } |
| 12 | + return combineTitleFirstLast; |
| 13 | + } |
| 14 | + |
| 15 | + const customer1 = giveFullName(); |
| 16 | + console.log(customer1); |
| 17 | + |
| 18 | + let firstName = 'Max'; |
| 19 | + console.log(customer1("Mr.", "John", "Smith")) |
| 20 | + |
| 21 | + |
5 | 22 | // ==== Challenge 2: Create a counter function ==== |
6 | 23 | const counter = () => { |
7 | 24 | // Return a function that when invoked increments and returns a counter variable. |
| 25 | + let x = 0; |
| 26 | + const increment = function() { |
| 27 | + x = x + 1; |
| 28 | + return x; |
| 29 | + } |
| 30 | + return increment; |
8 | 31 | }; |
| 32 | + |
9 | 33 | // Example usage: const newCounter = counter(); |
10 | 34 | // newCounter(); // 1 |
11 | 35 | // newCounter(); // 2 |
12 | 36 |
|
| 37 | +const newCounter = counter(); |
| 38 | +console.log(newCounter); |
| 39 | + |
| 40 | +console.log(newCounter()); |
| 41 | +console.log(newCounter()); |
| 42 | +console.log(newCounter()); |
| 43 | + |
| 44 | + |
13 | 45 |
|
14 | 46 | // ==== Challenge 3: Create a counter function with an object that can increment and decrement ==== |
| 47 | + |
15 | 48 | const counterFactory = () => { |
16 | 49 | // Return an object that has two methods called `increment` and `decrement`. |
17 | 50 | // `increment` should increment a counter variable in closure scope and return it. |
18 | 51 | // `decrement` should decrement the counter variable and return it. |
19 | | -}; |
| 52 | + let a = 0; |
| 53 | + let newObject = { |
| 54 | + increment: function() { |
| 55 | + a = a + 1; |
| 56 | + return a; |
| 57 | + }, |
| 58 | + decrement: function() { |
| 59 | + a = a - 1; |
| 60 | + return a; |
| 61 | + }, |
| 62 | + }; |
| 63 | + return newObject; |
| 64 | +} |
| 65 | + |
| 66 | +const adderSubtractor = counterFactory() |
| 67 | +console.log(adderSubtractor); |
| 68 | + |
| 69 | +console.log(adderSubtractor.increment()); |
| 70 | +console.log(adderSubtractor.increment()); |
| 71 | +console.log(adderSubtractor.increment()); |
| 72 | +console.log(adderSubtractor.decrement()); |
| 73 | +console.log(adderSubtractor.decrement()); |
| 74 | +console.log(adderSubtractor.decrement()); |
| 75 | +console.log(adderSubtractor.decrement()); |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + |
| 80 | + |
| 81 | + |
| 82 | + |
0 commit comments