Cloning Utilities API reference for object and array cloning functions copy Guide

Cloning Utilities

The Cloning utilities provide functions for creating copies of objects and arrays in JavaScript. These functions offer ways to create shallow or deep copies of data structures, which is crucial for avoiding unintended side effects when working with complex objects.

Functions

clone

function clone(src, seen = new Map())

Creates a deep clone of the provided value.

Handling Complex Structures This function can clone arrays, objects, dates, regular expressions, maps, and sets. It also handles circular references to prevent infinite recursion.

Parameters

NameTypeDescription
srcanyThe value to clone
seenMapInternal use. A Map to keep track of circular references

Returns

A deep clone of the input value.

Example

import { clone } from '@semantic-ui/utils';
const original = {
a: 1,
b: { c: 2 },
d: [1, 2, 3],
e: new Date(),
f: /test/gi
};
const cloned = clone(original);
console.log(cloned); // { a: 1, b: { c: 2 }, d: [1, 2, 3], e: Date, f: /test/gi }
console.log(cloned !== original); // true
console.log(cloned.b !== original.b); // true
console.log(cloned.d !== original.d); // true

extend

function extend(obj, ...sources)

Extends an object with properties from other objects, properly handling getter/setters.

Descriptor Handling This function uses Object.getOwnPropertyDescriptor and Object.defineProperty to ensure that getters and setters are correctly copied, preserving their behavior in the extended object.

Parameters

NameTypeDescription
objobjectThe target object to extend
sources…objectOne or more source objects

Returns

The extended object.

Example

import { extend } from '@semantic-ui/utils';
const target = { a: 1 };
const source1 = {
b: 2,
get c() { return this.b * 2; }
};
const source2 = { d: 4 };
const result = extend(target, source1, source2);
console.log(result); // { a: 1, b: 2, d: 4 }
console.log(result.c); // 4