JavaScript : Clone an object in JavaScript with Doppel
by Developer @ pebbl.co.uk on Thursday, 9 May 2013
With all my recent work towards Describe.js there have been a few mini functionalities that I've been able to generalise, ExpReg was one, Doppel is another. I've seen many deep clone methods in my time, but for Describe I needed the option to change the way the cloning was accomplished on a per usage basis. This might be quite a specific use-case, but there's no harm in putting it up here as a separate piece of code.
Whilst the following design is obviously not optimal — calling a function for every clone operation is quite slow — it does offer a lot of flexibility and mean that external code can form part of the cloning process.
var objToClone, objDoppel;
objToClone = {'hello':{'abc':123}, 'world':{'def':'456'}};
objDoppel = Doppel(objToClone);
console.log( objDoppel ); /// an output that looks like objToClone
console.log( objDoppel.test ); /// undefined
objToClone.test = 'added';
console.log( objDoppel.test ); /// 'added'
Doppel is hardwired to use Doppel.IMPOSTOR by default. This descriptor attempts to create clones that inherit from their origin — as shown above. If you wish to override this behaviour you could just modify Doppel.IMPOSTOR any way you like, or, you could pass in another descriptor:
var objToClone, objDoppel;
objToClone = {'hello':{'abc':123}, 'world':{'def':'456'}};
objDoppel = Doppel(objToClone, Doppel.CLONE);
console.log( objDoppel.test ); /// undefined
objToClone.test = 'added';
console.log( objDoppel.test ); /// undefined
Essentially Doppel is a map function but for objects. If you so wished you could do something like this:
var objToClone, objDoppel;
objToClone = {'hello':{'abc':123}, 'world':{'def':'456'}};
objDoppel = Doppel(objToClone, {
'object' : function(){ return {}; }
'string' : function(e){
return e.target.replace('456', '654');
}
});
Which would result in a cloned object but with 'def':'456' being changed to 'def':'654'. Anyway, it's a random bit of code that someone else might find useful, so here it is:
/**
* Doppel 0.1
*
* Doppel is a system that can clone an object in a tailored way.
*
* @param obj : the object to be cloned
* @param behaviour : an object containing type-keys which
* describe what should be done for each
* var type found. See Doppel.IMPOSTOR or
* Doppel.CLONE for examples, you can pass
* your own object too.
* @param recurse : boolean if true will deep clone, if false
* will only clone the object passed. (not
* implemented fully yet, assume true)
*
* @author Phil Glanville - 2013/05
*/
var Doppel = (function(){
var g, describe, doppel, impostor, DoppelEvent;
/// DoppelEvent mimics a similar implementation of an Event object
/// an instance of this "event" is passed into each clone description
/// method, giving quite a bit of useful information, and allowing
/// that code to decide where the recursion stops.
DoppelEvent = function(target, parent, property, path){
/// the target object
this.target = target;
/// the parent of target
this.parent = parent;
/// property on the parent storing target
this.property = property;
/// a built recursive path of properties
this.path = path;
/// Doppel will continue to recurse if true
this.recurse = true;
};
DoppelEvent.prototype.preventRecursion = function(){
this.recurse = false;
};
DoppelEvent.prototype.allowRecursion = function(){
this.recurse = true;
};
/// the actual recursive worker function
g = function(obj, behaviour, recurse, work, parent, property, path){
var r,i,e,t = describe && describe.type
? describe.type(obj)
: typeof obj
;
if ( recurse ) {
e = new DoppelEvent(obj, parent, property, path);
/// just in case we've come across this object before.
/// @todo: would be good to find a more optimal way that
/// doesn't rely on modifying any src or dst object.
if ( (i=work.src.indexOf(obj)) !== -1 ||
(i=work.dst.indexOf(obj)) !== -1 ) {
return work.dst[i];
}
}
/// create our doppel
r = (i=behaviour[t]||behaviour['default']) ? i.call(this, e) : obj;
/// store for checks next time around
work.src.push( obj );
work.dst.push( r );
/// if we are still allowed to recurse
if ( e.recurse ) {
for( i in obj ) {
r[i] = g(obj[i], behaviour, recurse, work, obj, i, path+'/'+i);
}
}
return r;
};
/// the exposed function that will be Doppel()
doppel = function(obj, behaviour, recurse, work){
recurse = true; /// false mode is not fully implemented yet.
describe = typeof describe !== 'undefined'
? describe
: {type:function(o){return typeof o;}}
;
if ( arguments.length === 2 ){
if ( behaviour === true ) {
behaviour = doppel.IMPOSTOR;
recurse = true;
}
else if ( behaviour === false ) {
behaviour = doppel.IMPOSTOR;
recurse = false;
}
else {
recurse = true;
}
}
else if ( arguments.length === 1 ){
recurse = true;
}
if ( !behaviour ){
behaviour = doppel.IMPOSTOR;
}
if ( recurse ) {
work = {src:[], dst:[]};
}
return g(obj, behaviour, recurse, work, null, null, '');
}
/**
* using the impostor description means that each of your
* clonable properties will inherit from the origin, but
* will essentially be a new object in-themselves.
*/
impostor = function(){};
doppel.IMPOSTOR = {
/// for objects, create a new instance with the origin inherited
'object' : function(e){
impostor.prototype = e.target; return new impostor();
},
/// please note function clone does not honour function.length
'function' : function(e){
return function(){e.target.apply(e.src, arguments);}
},
/// you could inherit an array from an array, but it would be weird
'array' : function(e){
return target.slice(0);
},
/// for anything else, return the origin
'default' : function(e){
e.preventRecursion();
return e.target;
}
};
/**
* The Clone description will actually create new objects for clonable
* items. These new items have no link to their origin what-so-ever.
* This is a very simple clone, if you wish to perform cloning of
* objects containing DOM Elements or other complex Native
* constructs I'd recommend building your own description object.
*/
doppel.CLONE = {
/// for objects, new object
'object' : function(e){
return {};
},
/// for arrays, slice clone
'array' : function(e){
return e.target.slice(0);
},
/// for anything else, leave as it is
'default' : function(e){
e.preventRecursion();
return e.target;
}
}
return doppel;
})();
- Leave your comment • Category: Coding, JavaScript
- Share on Twitter, Facebook, Delicious, Digg, Reddit