-
Notifications
You must be signed in to change notification settings - Fork 0
/
nest-object-hard-copy.min.js
1 lines (1 loc) · 1.27 KB
/
nest-object-hard-copy.min.js
1
"use strict";var DEFAULT_CIRCULAR_VALUE="[Circular]";function setDeep(e,r,i){var t=0;r.reduce((e,n)=>++t===r.length?(e[n]=i,i):e[n],e)}function getDeep(e,r){return e.reduce(function(e,r){return e[r]},r)}function checkCircular(e){var r=!1;try{JSON.parse(JSON.stringify(e))}catch(e){e instanceof TypeError&&-1!==e.message.indexOf("Converting circular structure to JSON")&&(r=!0)}return r}function isNonePrimitive(e){return"object"==typeof e&&e&&null!==e&&!Array.isArray(e)}function getKeyChains(e){var r=[],i=[],t=[],n=checkCircular(e),c=[e];return Object.keys(e).forEach(u=>{var o=e[u];if(isNonePrimitive(o)){if(n){if(c.indexOf(o)>-1)return void t.push([u]);c.push(o)}i=[u],function e(r){Object.keys(r).forEach(u=>{var o=r[u];if(isNonePrimitive(o)){if(n){if(c.indexOf(o)>-1)return void t.push([...i,u]);i.push(u),c.push(o)}return i.push(u),void e(r[u])}})}(e[u]),r.push([...i])}else r.push([u])}),{keyChain:r,circularKeyChain:t}}function deepCopy(e){var r=Object.assign({});r.__proto__=Object.getPrototypeOf(e);var i=getKeyChains(e),t=i.keyChain,n=i.circularKeyChain;return t.forEach(i=>{r[i[0]]={...e[i[0]]},i.forEach((t,n)=>{var c=[...i].slice(0,n+1),u=getDeep(c,e);setDeep(r,c,isNonePrimitive(u)?{...u}:u)})}),n.length&&n.forEach(e=>{setDeep(r,e,DEFAULT_CIRCULAR_VALUE)}),r}module.exports=deepCopy;