import { assert } from 'vitest'
import { JsonSchema } from '@traversable/json-schema'
const deepClone = JsonSchema.deepClone({
type: 'object',
required: ['street1', 'city'],
properties: {
street1: { type: 'string' },
street2: { type: 'string' },
city: { type: 'string' },
}
})
const sherlock = { street1: '221 Baker St', street2: '#B', city: 'London' }
const harry = { street1: '4 Privet Dr', city: 'Little Whinging' }
const sherlockCloned = deepClone(sherlock)
const harryCloned = deepClone(harry)
// values are deeply equal:
assert.deepEqual(sherlockCloned, sherlock) // ✅
assert.deepEqual(harryCloned, harry) // ✅
// values are fresh copies:
assert.notEqual(sherlockCloned, sherlock) // ✅
assert.notEqual(harryCloned, harry) // ✅
JsonSchema.deepClone
Derive a deep clone function from a zod schema (v4, classic).
The generated cloning function is significantly faster than JavaScript's built-in structuredClone
structuredClone
:It's even faster when compared with Lodash's
cloneDeep
:This is possible because the cloning function knows the shape of your data ahead of time, and will do the minimum amount of work necessary to create a new copy of your data.
Note that the "deep clone function" generated by
JsonSchema.deepClone
assumes that both values have already been validated. Passing invalid data to the clone function will result in undefined behavior.Note that
JsonSchema.deepClone
works in any environment that supports defining functions using theFunction
constructor. If your environment does not support theFunction
constructor, useJsonSchema.deepClone.writeable
.See also:
JsonSchema.deepClone.writeable