Skip to content

Commit be2f09b

Browse files
committed
closure done
1 parent 82512b4 commit be2f09b

1 file changed

Lines changed: 20 additions & 1 deletion

File tree

src/closure.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,28 +5,47 @@ const counter = () => {
55
// Example: const newCounter = counter();
66
// newCounter(); // 1
77
// newCounter(); // 2
8+
let count = 0;
9+
return () => ++count;
810
};
911

1012
const counterFactory = () => {
1113
// Return an object that has two methods called `increment` and `decrement`.
1214
// `increment` should increment a counter variable in closure scope and return it.
1315
// `decrement` should decrement the counter variable and return it.
16+
let count = 0;
17+
return {
18+
increment: () => ++count,
19+
decrement: () => --count,
20+
};
1421
};
1522

1623
const limitFunctionCallCount = (cb, n) => {
1724
// Should return a function that invokes `cb`.
1825
// The returned function should only allow `cb` to be invoked `n` times.
26+
let timesCalled = 0;
27+
return (...args) => {
28+
if (timesCalled === n) return null;
29+
timesCalled++;
30+
return cb(...args);
31+
};
1932
};
2033

2134
/* STRETCH PROBLEM */
2235

2336
const cacheFunction = (cb) => {
24-
// Should return a funciton that invokes `cb`.
37+
// Should return a function that invokes `cb`.
2538
// A cache (object) should be kept in closure scope.
2639
// The cache should keep track of all arguments have been used to invoke this function.
2740
// If the returned function is invoked with arguments that it has already seen
2841
// then it should return the cached result and not invoke `cb` again.
2942
// `cb` should only ever be invoked once for a given set of arguments.
43+
const cache = {};
44+
return (input) => {
45+
if (Object.prototype.hasOwnProperty.call(cache, input)) return cache[input];
46+
cache[input] = cb(input);
47+
return cache[input];
48+
};
3049
};
3150

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

0 commit comments

Comments
 (0)