UNPKG

immutable-js

Version:
63 lines (58 loc) 2.07 kB
/** * Copyright (c) 2015, Jan Biasi. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ export default function clone(item) { if (!item) { // null, undefined values check return item; } var types = [Number, String, Boolean], result; // normalizing primitives if someone did new String('aaa'), or new Number('444'); types.forEach(function(type) { if (item instanceof type) { result = type(item); } }); if (typeof result === 'undefined') { if (Object.prototype.toString.call(item) === '[object Array]') { result = []; item.forEach(function(child, index, array) { result[index] = clone(child); }); } else if (typeof item === 'object') { // testing that this is DOM if (item.nodeType && typeof item.cloneNode === 'function') { 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) { if(item.hasOwnProperty(i)) { result[i] = clone(item[i]); } } } } else { // depending what you would like here, // just keep the reference, or create new object if (false && item.constructor) { result = Object.create(item.prototype); } else { result = item; } } } else { result = item; } } return result; }