Skip to content

Commit 199f347

Browse files
authored
Merge pull request #3 from kabeh2/closure
Completed closure problems
2 parents ffcf44a + bca97ff commit 199f347

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

assignments/closure.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,69 @@
11
// ==== Challenge 1: Write your own closure ====
22
// Write a simple closure of your own creation. Keep it simple!
33

4+
function addNumbers() {
5+
// Local free variable
6+
let x = 1;
7+
8+
function sumNumbers() {
9+
let y = 2;
10+
console.log(`The new sum is: ${x + y}`);
11+
}
12+
13+
// Here shows the global variable can be manipulated outside the environment record
14+
x++;
15+
16+
return sumNumbers;
17+
}
18+
19+
let z = addNumbers();
20+
z();
421

522
// ==== Challenge 2: Create a counter function ====
623
const counter = () => {
724
// Return a function that when invoked increments and returns a counter variable.
25+
26+
let counter = 0;
27+
28+
function countUp() {
29+
counter++;
30+
console.log(`The new count is: ${counter}`);
31+
}
32+
33+
return countUp;
834
};
35+
936
// Example usage: const newCounter = counter();
1037
// newCounter(); // 1
1138
// newCounter(); // 2
1239

40+
let plusCounter = counter();
41+
plusCounter();
42+
plusCounter();
43+
1344
/* STRETCH PROBLEM, Do not attempt until you have completed all previous tasks for today's project files */
1445

1546
// ==== Challenge 3: Create a counter function with an object that can increment and decrement ====
1647
const counterFactory = () => {
1748
// Return an object that has two methods called `increment` and `decrement`.
1849
// `increment` should increment a counter variable in closure scope and return it.
1950
// `decrement` should decrement the counter variable and return it.
51+
let counter = 0;
52+
return {
53+
increment: function() {
54+
let result = counter++;
55+
return result;
56+
},
57+
decrement: function() {
58+
let result = counter--;
59+
return result;
60+
}
61+
};
2062
};
63+
64+
let number = counterFactory();
65+
number.increment();
66+
number.increment();
67+
number.increment();
68+
number.decrement();
69+
console.log(`The new stretch number count is: ${number.increment()}`);

0 commit comments

Comments
 (0)