-
Notifications
You must be signed in to change notification settings - Fork 814
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding Support for _.cloneDeep using recursiveClone #306
base: master
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would break if we pass null
.
Co-authored-by: Vitor Luiz Cavalcanti <[email protected]>
Co-authored-by: Vitor Luiz Cavalcanti <[email protected]>
This breaks on an object with circular references const object = {
'bar': {},
'foo': { 'b': { 'c': { 'd': {} } } },
};
object.foo.b.c.d = object;
object.bar.b = object.foo.b;
cloneDeep(object);
|
Here's the function cloneDeep(obj, hash = new WeakMap()) {
if (Object(obj) !== obj || obj instanceof Function) {
return obj;
}
if (hash.has(obj)) {
return hash.get(obj);
}
let result: any;
try { // Try to run constructor without arguments
result = new obj.constructor();
} catch (e) {
result = Object.create(Object.getPrototypeOf(obj));
}
if (obj instanceof Map) {
Array.from(obj, ([key, val]) => result.set(cloneDeep(key, hash), cloneDeep(val, hash)));
} else if (obj instanceof Set) {
Array.from(obj, (key) => result.add(cloneDeep(key, hash)));
}
hash.set(obj, result);
return Object.assign(result, ...Object.keys(obj).map(key => ({ [key]: cloneDeep(obj[key], hash) })));
}; |
Yes, an unusual use case so I didn't adapt for it. Just in case we want to support that: const recursiveClone = (src, hash = new WeakMap()) => {
if (src === null || typeof src !== 'object') { // for primitives / functions / non-references/pointers
return src
}
if (hash.has(obj)) {
return hash.get(obj);
}
let result;
if (Array.isArray(src)) { // for arrays
result = src.map(element => recursiveClone(element, hash))
}
result = Object.fromEntries(
Object.entries(src).map(
([key, val]) => ([key, recursiveClone(val, hash)])
)
)
hash.set(src, result);
return result;
} In case we also want to support things like Maps & Sets we could too. |
Unfortunately the project I was working on did need all the edge cases, but I'm glad there's a good simplified version |
Is |
Awesome find. I think people may complain that it lacks support for functions, but I don't often see the need for that piece of functionality. |
5559a1c
to
bd9b25e
Compare
Supports _.cloneDeep as discussed in Issue: #121.