A deep dive in the Vue.js source code (#8): the cached function

The cached function creates a cached version of a pure function.

This is the eighth post in a series examining the Vue.js source code line-by-line. In the last post, we began to examine the normalizeProps function. In this post, we take a quick detour to examine the background necessary to understand the camelize function. Before we can understand the camelize function, we must first examine the cached function.

The cached function is a utility function that creates “a cached version of a pure function.”

function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}

The cached function takes a function as a parameter:

function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}

Then initializes a variable cache and sets it to an empty object:

function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}

And then returns a function (thereby creating a closure) which takes a string as a parameter:

function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}

When the returned function is called, it initializes a variable hit and sets it to the str property on cache:

function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}

If hit exists (i.e., if the cached function has previously been called with this string as a parameter), then it returns hit. Otherwise, the function maps the str property on cache as the result of calling the fn function and passing str.

function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}

This is an elegant way of caching prior function calls. The returned function has access to the fn parameter and the cache variable through a closure. Each time the returned function is called, a new property/key may be added to the cache object. If the property already exists, the function just returns the results rather than do the computations of the function again. If the property does not exist, it calls the function, sets the property, and returns it.

With this background, we will be able to examine the camelize function in the next post.

If you like the series and want to motivate me to keep working through it, please feel free to clap, follow, respond, or share to your heart’s content.

Next Post: