@@ -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
1012const 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
1623const 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
2336const 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