@traversable/schema
    Preparing search index...
    • Derive a "deep clone" function from a valibot schema.

      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 deepCloneDeep:

      • ~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 vx.deepClone assumes that both values have already been validated. Passing invalid data to the deepClone function will result in undefined behavior.

      Note that vx.deepClone works in any environment that supports defining functions using the Function constructor. If your environment does not support the Function constructor, use vx.deepClone_writeable.

      See also:

      Type Parameters

      • S extends BaseSchema<unknown, unknown, any>
      • T = InferOutput<S>

      Parameters

      • schema: S

      Returns (cloneMe: T) => T

      import { assert } from 'vitest'
      import * as v from 'valibot'
      import { vx } from '@traversable/valibot'

      const deepClone = vx.deepClone(
      v.object({
      street1: v.string(),
      street2: v.optional(v.string()),
      city: v.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) // ✅