Skip to content

Commit 32069e6

Browse files
committed
finished with closure portion of the JavaScript-II assignment
1 parent deb9cb6 commit 32069e6

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed

assignments/closure.js

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,81 @@
22
// Write a simple closure of your own creation. Keep it simple!
33

44

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+
522
// ==== Challenge 2: Create a counter function ====
623
const counter = () => {
724
// 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;
831
};
32+
933
// Example usage: const newCounter = counter();
1034
// newCounter(); // 1
1135
// newCounter(); // 2
1236

37+
const newCounter = counter();
38+
console.log(newCounter);
39+
40+
console.log(newCounter());
41+
console.log(newCounter());
42+
console.log(newCounter());
43+
44+
1345

1446
// ==== Challenge 3: Create a counter function with an object that can increment and decrement ====
47+
1548
const counterFactory = () => {
1649
// Return an object that has two methods called `increment` and `decrement`.
1750
// `increment` should increment a counter variable in closure scope and return it.
1851
// `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

Comments
 (0)