I have been a bit of difficult time wrapping my head around closures. The first task was kinda simple, but the tasks 2 & 3 I struggled for a while. I did further reading on closures in the MDN Docs and was able to kinda work my way through those.
Can’t say the same about task 4 - I am completely stumped here. I gave it couple of tries and this is my best effort so far.
export function memoizeTransform(f) {
const cache = {coordinates: 0, result: 0};
return function(a, b) {
if (cache.coordinates[0] == a && cache.coordinates[1] == b) {
return [cache.result[0], cache.result[1]];
}
else {
cache.coordinates = [a, b];
const transformed = f(a, b);
cache.result = transformed;
return f(a, b);
}
};
}
I don’t know how to accept the final arguments (a, b) without calling the “memoized function” to just compare them with the stored values.
I guess, I don’t really understand how I can store the previous results and how to memoize a function.
I think your solution has the right idea. A closure is just a non-local variable that the function can read and write but others can’t.
You could’ve created more than one variable, like a memoCoordinates and a memoResult, instead of just one cache. But the overall structure is the same.
Just notice that right now you assume that f(a,b) is an Array. That might be the case here, I don’t remember.
You could ask for mentorship to ask those questions. Then someone more experienced could address this and other aspects of your code as well.
The tests are a bit tricky. The function f that you receive actually counts how many times it gets called, and the tests expect the function to be called a certain number of times. Here you’re calling it (needlessly) twice. You already have the result of the function, you can return that value.
I solved this one backwards because I was having difficultly figuring out what I needed to do. I wrote the transformation function first and then step by step worked my way back to storing the values, and in that I called the function unnecessarily and didn’t think too much about it.
I didn’t realize that function f had an internal counter. That makes a lot more sense now. Thanks!