Skip to content

Instantly share code, notes, and snippets.

@ozkansen
Created February 22, 2021 19:07
Show Gist options
  • Save ozkansen/5d52932cfc665d85d7458be11ae4d186 to your computer and use it in GitHub Desktop.
Save ozkansen/5d52932cfc665d85d7458be11ae4d186 to your computer and use it in GitHub Desktop.
// Fill inside of the optimizeFunction function
function doExpensiveTask(input) {
const result = 2 * input
console.log("Doing expensive task...:", result);
return result;
}
function optimizeFunction(func) {
/*
* Only write code in this function.
* This function returns an optimized version of the func
*/
var cache = {};
return function (k) {
if (k in cache) {
return console.log("Same input, no need to calculate: "+cache[k]);
} else {
cache = {};
var val = func.apply(this, arguments);
cache[k] = val;
return val;
}
}
}
// optimizedFunc shouldn't execute the expensive task if new input is same as the previous one
const optimizedFunc = optimizeFunction(doExpensiveTask);
optimizedFunc(2); // Should print: Doing expensive task...: 4
optimizedFunc(2); // Should print: Same input, no need to calculate: 4
optimizedFunc(4); // Should print: Doing expensive task...: 8
optimizedFunc(4); // Should print: Same input, no need to calculate: 8
optimizedFunc(2); // Should print ((Forgets the old one)): Doing expensive task...: 4
/*
* Fill inside of the makeFunctionWithFixedThis function
* You can use console.log for debugging purposes
* But, before submitting your answer you should remove any debug statements,
* only console.log statement should be in the printName method
*/
class Person {
constructor(firstName) {
this.firstName = firstName
}
printName() {
// This should be the only console.log statement in the submitted work
console.log(this.firstName)
}
}
const personA = new Person('AAA')
const personB = new Person('BBB')
// See that these statements doesn't print correct firstNames
setTimeout(personA.printName, 0)
setTimeout(personB.printName, 0)
function makeFunctionWithFixedThis(func, objToBeThis) {
/*
* only write code in this function
* This function returns a function with fixed 'this'
*/
return function () {
func.apply(objToBeThis);
}
}
const fixedPersonAPrint = makeFunctionWithFixedThis(personA.printName, personA)
const fixedPersonBPrint = makeFunctionWithFixedThis(personB.printName, personB)
// After implementing body of makeFunctionWithFixedThis,
// these setTimeout calls should print the firstNames correctly
setTimeout(fixedPersonAPrint, 0)
setTimeout(fixedPersonBPrint, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment