Skip to content

Commit

Permalink
scope variables to avoid unnecessary allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
planttheidea committed Sep 24, 2022
1 parent b2caf32 commit 12d168e
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,15 @@ export function copy<Value>(value: Value, options?: Options): Value {
return getObjectClone(value, realm, handleCopy, cache);
}

let clone: any;

// arrays
if (isArray(value)) {
// if strict, include non-standard properties
if (isStrict) {
return getObjectCloneStrict(value, realm, handleCopy, cache);
}

clone = new Constructor();
const clone = new Constructor();

cache.set(value, clone);

for (
Expand All @@ -113,7 +112,7 @@ export function copy<Value>(value: Value, options?: Options): Value {

// regexps
if (value instanceof realm.RegExp) {
clone = new Constructor(
const clone = new Constructor(
value.source,
value.flags || getRegExpFlags(value)
);
Expand All @@ -125,7 +124,8 @@ export function copy<Value>(value: Value, options?: Options): Value {

// maps
if (realm.Map && value instanceof realm.Map) {
clone = new Constructor();
const clone = new Constructor();

cache.set(value, clone);

value.forEach((value: any, key: any) => {
Expand All @@ -137,7 +137,8 @@ export function copy<Value>(value: Value, options?: Options): Value {

// sets
if (realm.Set && value instanceof realm.Set) {
clone = new Constructor();
const clone = new Constructor();

cache.set(value, clone);

value.forEach((value: any) => {
Expand All @@ -154,7 +155,7 @@ export function copy<Value>(value: Value, options?: Options): Value {

// buffers (node-only)
if (realm.Buffer && realm.Buffer.isBuffer(value)) {
clone = realm.Buffer.allocUnsafe
const clone = realm.Buffer.allocUnsafe
? realm.Buffer.allocUnsafe(value.length)
: new Constructor(value.length);

Expand All @@ -168,15 +169,19 @@ export function copy<Value>(value: Value, options?: Options): Value {
if (realm.ArrayBuffer) {
// dataviews
if (realm.ArrayBuffer.isView(value)) {
clone = new Constructor(value.buffer.slice(0));
const clone = new Constructor(value.buffer.slice(0));

cache.set(value, clone);

return clone;
}

// arraybuffers
if (value instanceof realm.ArrayBuffer) {
clone = value.slice(0);
const clone = value.slice(0);

cache.set(value, clone);

return clone;
}
}
Expand Down

0 comments on commit 12d168e

Please sign in to comment.