Implement a memoize function
Memoize function is a higher-order function which can cache the results of function calls and returns the cached result when it recieves the same inputs again. It may also be referred as cache function in few cases.
Basic implementation
Although the implementation of the memoize function in itself in quite straight forward, the most crucial part which might not seem obvious at first is generation of the cache keys, i.e, implementation of the generateCacheKey
method.
Generating effective cache keys
Working and creating an effective cache is always a tricky business. As it’s beyond the scope of the blog, I’ll only cover details which one might need to consider to discuss in an interview setting.
On first thought, one might approach generating keys using the join
method on arrays like :
const cacheKey=args.join('_')
, but that fails to consider two cases we can run into:
- Cache keys must be able to differentiate between
strings
andnumbers
, i.e, if the function could operate with both type of arguments, we want to treat the two inputsconst input=['Mike', 27]
andconst input=['Mike', '27']
, differently. Using the join methods would yield same key which is'Mike_27'
. - If the seperator used comes as argument, there can be a cache key collision, i.e,
['Hello', '_Mike']
and['Hello_', 'Mike']
, would yield the same cache key which is'Hello__Mike'
.
Surprisingly, the most easiest solution that handles both the cases is the good old JSON.stringify(args)
.
Note: JSON.stringify(args)
, although is quite effective to solve the problem of generate unique keys based on the arguments, one might need to consider that it is effectively slower on larger data sets. In cases like these, a more robust and fast solution can be created using the Trie
data structure.
I found this article by Christopher Alvear on Medium a very good starting point to learn about the same.
The implementation would be along the lines of:
Further Reading
I strongly encourage you to explore and tackle additional questions in my Closure Questions for Frontend Interviews blog series.
By doing so, you can enhance your understanding and proficiency with closures, preparing you to excel in your upcoming frontend interviews.
Wishing you best. Happy Interviewing 🫡.