Skip to content

Commit 1475c94

Browse files
SunJieMingSunJieMing
authored andcommitted
Added closure solutions
1 parent cc8dd35 commit 1475c94

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

src/closure.js

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,54 @@
11
// Complete the following functions.
22

3+
/* eslint-disable no-unused-vars */
4+
35
const counter = () => {
46
// Return a function that when invoked increments and returns a counter variable.
57
// Example: const newCounter = counter();
68
// newCounter(); // 1
79
// newCounter(); // 2
10+
let count = 0;
11+
return () => {
12+
count++;
13+
return count;
14+
};
815
};
916

1017
const counterFactory = () => {
1118
// Return an object that has two methods called `increment` and `decrement`.
1219
// `increment` should increment a counter variable in closure scope and return it.
1320
// `decrement` should decrement the counter variable and return it.
21+
let count = 0;
22+
return {
23+
increment: () => (++count),
24+
decrement: () => (--count),
25+
};
1426
};
1527

1628
const limitFunctionCallCount = (cb, n) => {
1729
// Should return a function that invokes `cb`.
1830
// The returned function should only allow `cb` to be invoked `n` times.
31+
let callCount = 0;
32+
return (...args) => {
33+
if (callCount === n) return null;
34+
callCount++;
35+
return cb(...args);
36+
};
1937
};
2038

21-
/* Extra Credit */
2239
const cacheFunction = (cb) => {
2340
// Should return a funciton that invokes `cb`.
2441
// A cache (object) should be kept in closure scope.
2542
// The cache should keep track of all arguments have been used to invoke this function.
2643
// If the returned function is invoked with arguments that it has already seen
2744
// then it should return the cached result and not invoke `cb` again.
2845
// `cb` should only ever be invoked once for a given set of arguments.
46+
const cache = {};
47+
return (input) => {
48+
if (Object.prototype.hasOwnProperty.call(cache, input)) return cache[input];
49+
cache[input] = cb(input);
50+
return cache[input];
51+
};
2952
};
3053

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

0 commit comments

Comments
 (0)