DEV Community

Discussion on: Create a memoized function in JavaScript

Collapse
 
davwheat profile image
David Wheatley

There is a MAJOR flaw with this design.

If you call memoizedAddFunction(1, 2, 3, 4), you'll get 10 as expected.

If you then decide to call memoizedAddFunction(123, 4), you'll still get 10!

This is because you used .join('') instead of .join(',') or .join(' ').

Ideally, you should use some unique hash of the array items instead of the items themselves, as this would break very badly if you wanted to memoize a function that accepted strings as input.

Collapse
 
jeremydmarx813 profile image
Jeremy Marx

join method now passing in a comma as a separator, so the function should work as planned. Thanks for the great feedback!

Collapse
 
jeremydmarx813 profile image
Jeremy Marx

That is a fair point, I will look in to another way to create the key on the cache.