|
1 | 1 | // Complete the following functions. |
2 | 2 |
|
| 3 | +/* eslint-disable no-unused-vars */ |
| 4 | + |
3 | 5 | const counter = () => { |
4 | 6 | // Return a function that when invoked increments and returns a counter variable. |
5 | 7 | // Example: const newCounter = counter(); |
6 | 8 | // newCounter(); // 1 |
7 | 9 | // newCounter(); // 2 |
| 10 | + let count = 0; |
| 11 | + return () => { |
| 12 | + count++; |
| 13 | + return count; |
| 14 | + }; |
8 | 15 | }; |
9 | 16 |
|
10 | 17 | const counterFactory = () => { |
11 | 18 | // Return an object that has two methods called `increment` and `decrement`. |
12 | 19 | // `increment` should increment a counter variable in closure scope and return it. |
13 | 20 | // `decrement` should decrement the counter variable and return it. |
| 21 | + let count = 0; |
| 22 | + return { |
| 23 | + increment: () => (++count), |
| 24 | + decrement: () => (--count), |
| 25 | + }; |
14 | 26 | }; |
15 | 27 |
|
16 | 28 | const limitFunctionCallCount = (cb, n) => { |
17 | 29 | // Should return a function that invokes `cb`. |
18 | 30 | // 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 | + }; |
19 | 37 | }; |
20 | 38 |
|
21 | | -/* Extra Credit */ |
22 | 39 | const cacheFunction = (cb) => { |
23 | 40 | // Should return a funciton that invokes `cb`. |
24 | 41 | // A cache (object) should be kept in closure scope. |
25 | 42 | // The cache should keep track of all arguments have been used to invoke this function. |
26 | 43 | // If the returned function is invoked with arguments that it has already seen |
27 | 44 | // then it should return the cached result and not invoke `cb` again. |
28 | 45 | // `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 | + }; |
29 | 52 | }; |
30 | 53 |
|
31 | 54 | /* eslint-enable no-unused-vars */ |
|
0 commit comments