Skip to content

Commit b229fc7

Browse files
committed
updated closure.js
1 parent 6bcdb5b commit b229fc7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/closure.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,42 @@ const counter = () => {
55
// Example: const newCounter = counter();
66
// newCounter(); // 1
77
// newCounter(); // 2
8+
let count = 0;
9+
return () => {
10+
count++;
11+
return count;
12+
};
813
};
914

1015
const counterFactory = () => {
1116
// Return an object that has two methods called `increment` and `decrement`.
1217
// `increment` should increment a counter variable in closure scope and return it.
1318
// `decrement` should decrement the counter variable and return it.
19+
let count = 0;
20+
return {
21+
increment: () => {
22+
count++;
23+
return count;
24+
},
25+
decrement: () => {
26+
count--;
27+
return count;
28+
}
29+
};
1430
};
1531

1632
const limitFunctionCallCount = (cb, n) => {
1733
// Should return a function that invokes `cb`.
1834
// The returned function should only allow `cb` to be invoked `n` times.
35+
let count = 0;
36+
const returnFunction = (...args) => {
37+
if (count === n) {
38+
return null;
39+
}
40+
count++;
41+
return cb(...args);
42+
};
43+
return returnFunction;
1944
};
2045

2146
const cacheFunction = (cb) => {
@@ -25,6 +50,14 @@ const cacheFunction = (cb) => {
2550
// If the returned function is invoked with arguments that it has already seen
2651
// then it should return the cached result and not invoke `cb` again.
2752
// `cb` should only ever be invoked once for a given set of arguments.
53+
const cache = {};
54+
const cached = (arg) => {
55+
if (Object.prototype.hasOwnProperty.call(cache, arg)) {
56+
return cache[arg];
57+
}
58+
return cache[arg] = cb(arg);
59+
};
60+
return cached;
2861
};
2962

3063
/* eslint-enable no-unused-vars */

0 commit comments

Comments
 (0)