JSFiddle - React, Tailwind, and code Playground
by tonyleeper
JavaScript
function clone(obj) {
var copy;
// null or undefined
if (obj === null || typeof obj === 'undefined') {
return obj;
}
// dates
if (Object.prototype.toString.call(obj) === '[object Date]') {
copy = new Date(obj);
return copy;
}
// arrays (recursive)
if (Array.isArray(obj)) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// objects (recursive on properties)
if (typeof obj === 'object') {
copy = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
copy[prop] = clone(obj[prop]);
}
}
return copy;
}
throw new Error('Unsupported type');
}
var d = new Date();
var clone = clone(d);
clone.setTime(0, 0, 0, 0);
console.log(d);
console.log(clone);
console.log(d === clone);