All files / src snapshot.js

100% Statements 65/65
100% Branches 20/20
100% Functions 3/3
100% Lines 65/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 661x 1x 1x 21x 21x 21x 21x 21x 6x 6x 15x 15x 21x 1x 21x 21x 21x 25x 24x 24x 24x 23x 24x 1x 1x 25x 1x 1x 25x 20x 21x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 53x 52x 53x 4x 4x 48x 53x 9x 9x 39x 39x 53x  
// based on https://github.com/lukeed/klona
import { kStaty } from './constants.js'
 
function snapshotProp (state, prop) {
  const value = dlv(state, prop)
 
  const staty = value?.[kStaty]
  if (staty) {
    return staty.getSnapshot()
  }
 
  return value
}
 
function dlv (obj, key) {
  let p
  for (p = 0; p < key.length; p++) {
    if (obj) {
      const staty = obj?.[kStaty]
      const k = key[p]
      if (staty) {
        obj = staty.getValueByProp(k)
      } else {
        obj = obj[k]
      }
    } else {
      return obj
    }
  }
  return obj
}
 
/**
 * Create an snapshot from the state
 *
 * @template {unknown} T
 * @overload
 * @param {T} state
 * @returns {T}
 *
 * @template {unknown} T
 * @overload
 * @param {T} state
 * @param {Array<string>} props
 * @returns {Array<unknown>}
 *
 * @template {unknown} T
 * @overload
 * @param {T} state
 * @param {string} props
 * @returns {unknown}
 */
export function snapshot (state, props) {
  if (!state[kStaty]) throw new Error('the snapshot requires a valid staty object')
 
  if (Array.isArray(props)) {
    return props.map(p => snapshotProp(state, p.split('.')))
  }
 
  if (typeof props === 'string') {
    return snapshotProp(state, props.split('.'))
  }
 
  return state[kStaty].getSnapshot()
}