If you’ve worked through JavaScript recursion primer and More recursion – parents and children you should be pretty comfortable with how recursion works by now. Now we’re going to apply it to create a simple version of jQuery.extend(). If you are not familiar with it, its a useful function that allows you merge multiple objects – usually used for setting default properties.

Let’s say you have this as the default parameters to something like a charts API

and you want to use most of those settings,  but make just a  couple of changes, with jQuery you can say

and you’ll get back an object like this

Deeper

So far pretty simple .. but you may need to go deeper into the object if there are properties beyond the first level.

Still not too bad, but you’d have to do this. So you can imagine if you continue this out to multiple levels, we have a good candidate for a solution involving recursion

The cUseful library

Many of the snippets in this section of the site are part of the cUseful library. You can find the details below. This extend function uses a couple of functions from that, and will be implemented there too if you want to use it from a library.

Get library info

The extend function

You use it like this

You can have as many default objects as you like and the result will be the merger of all those defaults applied to your options, very much like jQuery.extend().

So how to do it ?

Here’s the code. We’ll do a walkthrough later on once we’ve done some testing

Some tests

See if you can figure out how these cases should be handled.
and the results
Let’s check on our initial example.
and the result

Walkthrough

  • Since we have a variable number of arguments, we use the special arguments array like object to pick the up from – returning undefined if we don’t get any.
  • Pick up each of the objects from the arguments array, check that they are in fact objects, and set up the target from the first one, and note all of the extenders from which to apply their default values.
  • For each of those extenders, apply their defaults. We have to do it recursively as each property of each extender may have sub properties.
Here’s the recursive function – it calls itself with the properties at the current level if any of them are an object so that matching properties from the default objects can be applied. These are analogous to the children in JavaScript recursion primer
And that’s all there is to it. Happy recursing.

For more like this, see Google Apps Scripts Snippets

Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.