forked from bloominstituteoftechnology/JavaScript-II
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclosure.js
More file actions
46 lines (39 loc) · 1.8 KB
/
closure.js
File metadata and controls
46 lines (39 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// ==== Challenge 1: Write your own closure ====
// Write a closure of your own creation.
// Keep it simple! Remember a closure is just a function
// that manipulates variables defined in the outer scope.
// The outer scope can be a parent function, or the top level of the script.
let closureVar = 'Easy closures';
const ezFunc = function(ezFunc){
return console.log(closureVar);
}
ezFunc();
/* STRETCH PROBLEMS, Do not attempt until you have completed all previous tasks for today's project files */
// ==== Challenge 2: Implement a "counter maker" function ====
const counterMaker = () => {
// IMPLEMENTATION OF counterMaker:
// 1- Declare a `count` variable with a value of 0. We will be mutating it, so declare it using `let`!
// 2- Declare a function `counter`. It should increment and return `count`.
// NOTE: This `counter` function, being nested inside `counterMaker`,
// "closes over" the `count` variable. It can "see" it in the parent scope!
// 3- Return the `counter` function.
let count = 0;
function myCounter() {
count++
return count;
}
return myCounter;
};
// Example usage: const myCounter = counterMaker();
const myCounter = counterMaker();
console.log(myCounter()); // 1
console.log(myCounter()); // 2
// ==== Challenge 3: Make `counterMaker` more sophisticated ====
// It should have a `limit` parameter. Any counters we make with `counterMaker`
// will refuse to go over the limit, and start back at 1.
// ==== Challenge 4: Create a counter function with an object that can increment and decrement ====
const counterFactory = () => {
// Return an object that has two methods called `increment` and `decrement`.
// `increment` should increment a counter variable in closure scope and return it.
// `decrement` should decrement the counter variable and return it.
};