DEV Community

Memoization in a Nutshell

Pan Chasinga on July 14, 2018

If anyone had ever set eyes on Cracking the Coding Interviews (or any other books on algorithms), you might at least know what memoization is and w...
Collapse
 
asaaki profile image
Christoph Grabo

One fix needed:

if (n == 0 || n == 1) n;
Enter fullscreen mode Exit fullscreen mode

needs to be

if (n === 0 || n === 1) return n;
Enter fullscreen mode Exit fullscreen mode

(also uses === as best practice)

Otherwise an error happens:

RangeError: Maximum call stack size exceeded
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pancy profile image
Pan Chasinga

Oh, shoot! Thank you. I thought that could implicitly return.

About the === it's very funny because now we don't have to use == again, although it is totally fine for integers like this case.

Collapse
 
asaaki profile image
Christoph Grabo

===: Yeah, I just picked up this habit, as it is usually the safer option, especially when processing external/user input.

return: JS is one of the langs without implicit returns. Nevertheless in the middle of a function we need to be explicit anyway, since more code follows afterwards. If implicit returns were supported you could use an else block to avoid a keyword, but also not worth the effort.

Thread Thread
 
pancy profile image
Pan Chasinga

Yeah I was hoping es6 is closer to functional than this. The only way to get an implicit return from the last expression is a lambda function without brackets (containing a single expression).

let fun = () => 0;
fun()           // will return 0
Collapse
 
asaaki profile image
Christoph Grabo

And for the brain version:

if (brain[n] === undefined) {

Or undefined will be the only result.

Collapse
 
thiht profile image
Thibaut Rousseau

The parallel with AI is really weird. Memoization is just a form of cache for pure functions, it's way simpler than anything AI related

Collapse
 
pancy profile image
Pan Chasinga

You're probably right. However, I was trying to kind of wrap this concept of memory / caching with the "brain". So I was trying to suggest that even with a super smart AI doing this it would still use this technique to memorize.

Collapse
 
itsjzt profile image
Saurabh Sharma

I understand recursion well enough, I just open the blog and clap for it

'cause It takes time and effort to write

Collapse
 
pancy profile image
Pan Chasinga

Thank you!

Collapse
 
ben profile image
Ben Halpern

Nice overview Joe.

Collapse
 
pancy profile image
Pan Chasinga

Thanks Ben!