weak-map-with-values.spec.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { describe, expect, it } from 'vitest'
  2. import { WeakMapWithValues } from '../src/index.ts'
  3. describe('WeakMapWithValues', () => {
  4. it('looks up weak keys while iterating strongly retained values in insertion order', () => {
  5. const firstKey = {}
  6. const secondKey = {}
  7. const firstValue = { name: 'first' }
  8. const secondValue = { name: 'second' }
  9. const values = new WeakMapWithValues<object, { name: string }>()
  10. expect(values.get(firstKey)).toBeUndefined()
  11. expect(values.has(firstKey)).toBe(false)
  12. expect(values.set(firstKey, firstValue)).toBe(values)
  13. values.set(secondKey, secondValue)
  14. expect(values.get(firstKey)).toBe(firstValue)
  15. expect(values.has(secondKey)).toBe(true)
  16. expect([...values.values]).toEqual([firstValue, secondValue])
  17. })
  18. it('keeps an identical association and replaces its prior retained value', () => {
  19. const key = {}
  20. const firstValue = { name: 'first' }
  21. const replacement = { name: 'replacement' }
  22. const values = new WeakMapWithValues<object, { name: string }>()
  23. values.set(key, firstValue)
  24. values.set(key, firstValue)
  25. expect([...values.values]).toEqual([firstValue])
  26. values.set(key, replacement)
  27. expect(values.get(key)).toBe(replacement)
  28. expect([...values.values]).toEqual([replacement])
  29. })
  30. it('deletes one association and clears every lookup and retained value', () => {
  31. const firstKey = {}
  32. const secondKey = {}
  33. const values = new WeakMapWithValues<object, string>()
  34. values.set(firstKey, 'first').set(secondKey, 'second')
  35. expect(values.delete({})).toBe(false)
  36. expect(values.delete(firstKey)).toBe(true)
  37. expect(values.has(firstKey)).toBe(false)
  38. expect([...values.values]).toEqual(['second'])
  39. values.clear()
  40. expect(values.get(secondKey)).toBeUndefined()
  41. expect(values.has(secondKey)).toBe(false)
  42. expect([...values.values]).toEqual([])
  43. values.set(firstKey, 'again')
  44. expect(values.get(firstKey)).toBe('again')
  45. expect([...values.values]).toEqual(['again'])
  46. })
  47. })