Skip to content

Instantly share code, notes, and snippets.

@Youngestdev
Created October 16, 2019 08:28
Show Gist options
  • Select an option

  • Save Youngestdev/87a84304862bfc2247b703e9ea36323e to your computer and use it in GitHub Desktop.

Select an option

Save Youngestdev/87a84304862bfc2247b703e9ea36323e to your computer and use it in GitHub Desktop.
Frontend masters algorithm course exercise.
// 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