Shelving: Clone
Shelving Clone is a simple deep-clone algorithm. It only works with JSON-friendly values:
null
- Finite numbers (e.g.
123
or45.158
) - Strings (e.g.
'abc'
) - Booleans (e.g.
true
andfalse
) - Plain arrays (e.g. arrays whose constructor is
Array
) - Plain objects (e.g. objects whose constructor is
Object
)
It will throw a CloneError
for values that cannot be represented in JSON, such as:
undefined
- Infinite numbers (e.g.
Infinity
,-Infinity
andNaN
) Date
objects- Complex objects
Example: Cloning an object
; // Original value.const original = str: 'abc' obj: str: 'abc' arr: 1 2 3; // Clone it.const cloned = ; // Result: Objects are deep-cloned.original === cloned; // False.originalobj === clonedobj; // False.originalarr === clonedarr; // False. // Result: Properties are the same.originalstr === clonedstr; // True.originalobjstr === clonedobjstr; // True.originalarrlength === clonedarrlength; // True.
Example: Cloning a primative value
Primative values are not copied by reference in Javascript (so don't need to be cloned). As you'd expect values pass through clone()
transparently:
123 === ; // True.true === ; // True.'abc' === ; // True.
Example: Attempting to clone complex value
clone()
will throw a CloneError
if it cannot clone the specified value:
; // Attempt to clone.; // Throws CloneError("Value must be JSON-friendly...").
Example: Testing whether value is cloneable
As clone()
only works on JSON-friendly values, the cloneable()
function can be used to test whether a value can be cloned before passing it into clone()
and throwing an error:
; // Cloneable values.; // Returns true.; // Returns true.; // Returns true.; // Returns true. // Non-cloneable values.; // Returns false.; // Returns false.; // Returns false.; // Returns false.; // Returns false.