Monday, January 19, 2015

The Power of Apply and Call

A lot of people that use JavaScript don't understand (or even want to understand) the apply and call functions that are built into every function.

Or apply me maybe?
In combination with being a bit confusing, a lot of times you can get around them by just adding an additional parameter or some extra code here and there, and so you just ignore them.

I just ran across a situation that shows a great use case for apply and hopefully will help someone understand how to use it.

The scenario is I have two arrays.  One array of N points starting from 0 and one array of M points starting at an some positive integer X.  When my JS code handles array M, I want to insert and overwrite positions X...M.length + X of array N.  The brute force way would just be to loop through them all copying them as they go.  I thought about it for a bit and gave myself a quick reminder of what functions exist for a JS array.

I thought about concat, but that only appends to the end.  I thought about splice, but that only handles a list of parameters.  Then I remembered that JS already has that covered with apply.  Using apply will solve my issue of having an array instead of a list of parameters.  The code for this is pretty simple.  Given 2 arrays, and a position it will be this:
Array.prototype.splice.apply(array1, 
         [position, array2.length].concat(array2));

You might notice the [position, array2.length].concat code in there and wonder what that is.  Well the first 2 parameters to splice are the position and the # of elements to move.  The remaining parameters are the values to insert.  So using concat to add the two together will make the apply call work.

Here is a live example:



No comments:

Post a Comment