Sunday, 30 May 2010

Cloning arrays

On the other day I had the need to copy an Array. It was not the first time, but this time I had to make a temporary copy of another array, and put some new data in it and make some calculations.

In this process my need to change the original Array, was none.

The problem is that if you make something like this:

var myArray:Array=new Array("Blue", "Yellow");
var myCopyArray:Array=new Array();


myCopyArray=myArray;

... it works to some extent. You can also do this with concat or slice commands.
This method makes a shallow copy, which means that the copy only stores the reference to the original values, that is, it only stores the memory reference where the values are stored. This means that if you change one of the arrays, the other will change also... This was not what I meant.

I needed to make a hard copy of the array, change it, without changing the original. During the research, I found this generic solution presented in a webpage by Adobe at the following link:
https://www.adobe.com/livedocs/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000092.html

As always I transcript the code to here and make a brief explanation.

So the function looks like this:

import flash.utils.ByteArray;

function clone(source:Object):*
{
    var myBA:ByteArray = new ByteArray();
    myBA.writeObject(source);
    myBA.position = 0;
    return(myBA.readObject());
}
Basically what this does is it goes to the memory and gets what is stored in the place where the original Array is referenced. To get the original data and not the reference, it uses the ByteArray class and stores the data in the myBA:ByteArray object. The ByteArray class insures that it copies whatever is stored in the original Array, i.e, Numbers, String, DisplayObjects, whatever...

Pretty handy...