diff --git a/clone.js b/clone.js new file mode 100644 index 0000000..b45f27f --- /dev/null +++ b/clone.js @@ -0,0 +1,52 @@ +/** +* Clone object and all it's properties. +* Works recursively. +* +* @param {Object} obj Object to clone. +* @param {Mixed} seen For internal use only. Don't set. +* @return {Object} The clone. +*/ +export const clone = (obj, seen) => { + if (typeof obj !== 'object' || obj === null) { + return obj; + } + seen = seen || new Map(); + const lookup = seen.get(obj); + if (lookup) { + return lookup; + } + let newObj; + let cloneDeep = false; + if (!Array.isArray(obj)) { + if (obj instanceof Date) { + newObj = new Date(obj.getTime()); + } else if (obj instanceof RegExp) { + newObj = new RegExp(obj); + } else { + const proto = Object.getPrototypeOf(obj); + if (proto && Object.isFrozen(obj)) { + newObj = obj; + } else { + newObj = Object.create(proto); + cloneDeep = true; + } + } + } else { + newObj = []; + cloneDeep = true; + } + seen.set(obj, newObj); + if (cloneDeep) { + const keys = Object.getOwnPropertyNames(obj); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + const descriptor = Object.getOwnPropertyDescriptor(obj, key); + if (descriptor && (descriptor.get || descriptor.set)) { + Object.defineProperty(newObj, key, descriptor); + } else { + newObj[key] = this._clone(obj[key], seen); + } + } + } + return newObj; +}; diff --git a/package.json b/package.json index f121e5f..cf59f25 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@tp/helpers", - "version": "1.0.2", + "version": "1.1.0", "description": "", "main": "closest.js", "scripts": { diff --git a/reach.js b/reach.js new file mode 100644 index 0000000..3dc45c0 --- /dev/null +++ b/reach.js @@ -0,0 +1,11 @@ +export const reach = (path, data) => { + const parts = path.split('.'); + let part; + while (part = parts.shift()) { + data = data instanceof Set || data instanceof Map ? data.get(part) : data[part]; + if (parts.length > 0 && (typeof data !== 'object' || data === null)) { + return; + } + } + return data; +}