@traversable/schema
    Preparing search index...
    • 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:

      • ~3x faster with shallow schemas
      • ~10x faster with large schemas

      It's even faster when compared with Lodash's cloneDeep:

      • ~9x faster with shallow schemas
      • ~25x faster with large schemas

      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 the Function constructor. If your environment does not support the Function constructor, use JsonSchema.deepClone.writeable.

      See also:

      Type Parameters

      Parameters

      • schema: S

      Returns (cloneMe: T) => T

      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) // ✅