Created
October 16, 2019 08:28
-
-
Save Youngestdev/87a84304862bfc2247b703e9ea36323e to your computer and use it in GitHub Desktop.
Frontend masters algorithm course exercise.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Task 1: Write a function, times10, that takes an argument, n, and multiples n times 10 | |
| // a simple multiplication fn | |
| const times10 = (n) => { | |
| return n * 10 | |
| }; | |
| console.log('~~~~~~~~~~~~~~TASK 1~~~~~~~~~~~~~~'); | |
| console.log('times10 returns:', times10(9)); | |
| // Task 2: Use an object to cache the results of your times10 function. | |
| // protip 1: Create a function that checks if the value for n has been calculated before. | |
| // protip 2: If the value for n has not been calculated, calculate and then save the result in the cache object. | |
| const cache = {}; | |
| const memoTimes10 = (n) => { | |
| if (n in cache) { | |
| console.log("Fetching from cache") | |
| return cache[n] | |
| } else { | |
| console.log("Not in cache, calculating values.") | |
| let result = times10(n) | |
| cache[n] = result | |
| return result | |
| } | |
| } | |
| console.log('~~~~~~~~~~~~~~TASK 2~~~~~~~~~~~~~~'); | |
| console.log('Task 2 calculated value:', memoTimes10(9)); // calculated | |
| console.log('Task 2 cached value:', memoTimes10(9)); // cached | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment