import { JsonSchema } from '@traversable/json-schema'
const deepClone = JsonSchema.deepClone.writeable({
type: 'object',
required: ['street1', 'city'],
properties: {
street1: { type: 'string' },
street2: { type: 'string' },
city: { type: 'string' },
}
}, { typeName: 'Type' })
console.log(deepClone)
// =>
// type Address = { street1: string; street2?: string; city: string; }
// function clone(prev: Address): Address {
// return {
// street1: prev.street1,
// ...prev.street2 !== undefined && { street2: prev.street2 },
// city: prev.city
// }
// }
JsonSchema.deepClone.writeable
Derive a "writeable" (stringified) deep clone function from a JSON Schema spec.
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.writeable
assumes that both values have already been validated. Passing invalid data to the clone function will result in undefined behavior. You don't have to worry about this as long as youJsonSchema.deepClone.writeable
accepts an optional configuration object as its second argument; documentation for those options are available via hover on autocompletion.See also:
JsonSchema.deepClone