Creating a Function Factory as a real world example

We can take advantage of the closure behaviour by creating a function that, depending on the arguments passed, returns a function with a different execution logic. The simplest example I can think of would be a factory that will return the power of n for a given number. The result would be the same as calling Math.pow(subject, power)

Simplest function factory

What this snippet does is create a dynamic function, in essence a function whose algorithm is not explicitly defined in the code itself but rather at run-time when it’s created with the arguments passed to the factory. Of course with the previous example you might be thinking that it’s rather useless and you’d be right, but what you need to grasp is the potential this functionality has.

We can now define a function that gives us the power of two by simply calling var powerOf2 = powerOfNFactory(2) . The internal generatedFunction will keep a closure over the power variable and will be completely independent from other calls to powerOfNFactory . This means we can extend the functionality and do things such as keeping track of the number of times our dynamic function was called, adding memoization (caching the results in order to prevent the repeated execution when called with the same arguments) and much more.

Adding the counter

The same way our dynamic function has access to the argument passed to the factory function, it will have access to anything defined inside of it just like on the first example with the counter, allowing us to define a simple counter and in doing so keep track of the times we’ve called this. Maybe you’d like to do this for logging purposes, maybe you’d want to limit the number of times a certain functionality can be executed before you do something else, up to you.

We keep an internal counter for the dynamic function

Memoization

Since the code executed inside our function is not expensive in terms of time we shouldn’t have to worry about caching its execution but it’s easier to show it here that it would be on a more extensive example so bare with me. This is useful for operations that will always return the same value when called with the same arguments but take more resources in terms of execution time for example

We keep an internal object acting as a dictionary cache