From 9f024d3a3d9cc203402246f7059eb77bca5a143d Mon Sep 17 00:00:00 2001 From: Onoshko Dan Date: Sun, 20 Apr 2014 01:42:58 +0700 Subject: [PATCH] Utils updated. --- lib/utils.js | 72 +++++++++++++++++++++------------------------------- 1 file changed, 29 insertions(+), 43 deletions(-) diff --git a/lib/utils.js b/lib/utils.js index 1c8e12a7..21b5b465 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -303,52 +303,38 @@ Cola.Dictionary.prototype = { }; Cola.clone = function (item) { - if (!item) { return item; } // null, undefined values check + if (item === undefined || item === null) return item; - var types = [ Number, String, Boolean ], - result; + var result, types = [ Number, String, Boolean ]; - // normalizing primitives if someone did new String('aaa'), or new Number('444'); - types.forEach(function(type) { - if (item instanceof type) { - result = type( item ); - } - }); + for (var i in types) + if(types.hasOwnProperty(i) && item instanceof types[i]) + return type( item ); - if (typeof result == "undefined") { - if (Object.prototype.toString.call( item ) === "[object Array]") { - result = []; - item.forEach(function(child, index, array) { - result[index] = Cola.clone( child ); - }); - } else if (typeof item == "object") { - // testing that this is DOM - if (item.nodeType && typeof item.cloneNode == "function") { - var result = item.cloneNode( true ); - } else if (!item.prototype) { // check that this is a literal - if (item instanceof Date) { - result = new Date(item); - } else { - // it is an object literal - result = {}; - for (var i in item) { - result[i] = Cola.clone( item[i] ); - } - } - } else { - // depending what you would like here, - // just keep the reference, or create new object - if (false && item.constructor) { - // would not advice to do that, reason? Read below - result = new item.constructor(); - } else { - result = item; - } - } - } else { - result = item; - } + if (item.__proto__ === Array.prototype) { + result = []; + item.forEach(function(child, index, array) { + result[index] = Cola.clone( child ); + }); + + return result; + } + + if (!(item instanceof Object)) return item; + + if (item.nodeType && item.cloneNode instanceof Function) return item.cloneNode( true ); + + if (!item.prototype) { + if (item instanceof Date) return new Date(item); + if (item instanceof Function) return item; + if (item.clone instanceof Function) return item.clone(); + + result = {}; + for (var i in item) result[i] = Cola.clone( item[i] ); + result.__proto__ = item.__proto__; + + return result; } - return result; + return item; }; \ No newline at end of file