1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-12 00:54:02 -05:00

webutil: replace cloneValue impl with serialize/deserialize (#10215)

Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
This commit is contained in:
Elad Keyshawn 2021-06-05 16:57:51 +03:00 committed by GitHub
parent 1d070f3d47
commit 4b3d55b449
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -35,29 +35,8 @@
/** Clone a value in a similar way to structured cloning. It is similar to a /** Clone a value in a similar way to structured cloning. It is similar to a
* StructureDeserialize(StructuredSerialize(...)). */ * StructureDeserialize(StructuredSerialize(...)). */
function cloneValue(value) { function cloneValue(value) {
switch (typeof value) { // Performance optimization for buffers, otherwise
case "number": // `serialize/deserialize` will allocate new buffer.
case "string":
case "boolean":
case "undefined":
case "bigint":
return value;
case "object": {
if (objectCloneMemo.has(value)) {
return objectCloneMemo.get(value);
}
if (value === null) {
return value;
}
if (value instanceof Date) {
return new Date(value.valueOf());
}
if (value instanceof RegExp) {
return new RegExp(value);
}
if (value instanceof SharedArrayBuffer) {
return value;
}
if (value instanceof ArrayBuffer) { if (value instanceof ArrayBuffer) {
const cloned = cloneArrayBuffer( const cloned = cloneArrayBuffer(
value, value,
@ -86,35 +65,14 @@
length, length,
); );
} }
if (value instanceof Map) {
const clonedMap = new Map();
objectCloneMemo.set(value, clonedMap);
value.forEach((v, k) => {
clonedMap.set(cloneValue(k), cloneValue(v));
});
return clonedMap;
}
if (value instanceof Set) {
// assumes that cloneValue still takes only one argument
const clonedSet = new Set([...value].map(cloneValue));
objectCloneMemo.set(value, clonedSet);
return clonedSet;
}
// default for objects try {
const clonedObj = {}; return Deno.core.deserialize(Deno.core.serialize(value));
objectCloneMemo.set(value, clonedObj); } catch (e) {
const sourceKeys = Object.getOwnPropertyNames(value); if (e instanceof TypeError) {
for (const key of sourceKeys) { throw new DOMException("Uncloneable value", "DataCloneError");
clonedObj[key] = cloneValue(value[key]);
} }
Reflect.setPrototypeOf(clonedObj, Reflect.getPrototypeOf(value)); throw e;
return clonedObj;
}
case "symbol":
case "function":
default:
throw new DOMException("Uncloneable value in stream", "DataCloneError");
} }
} }