Advertisement
kauffman12

jsserialize

Nov 1st, 2023 (edited)
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 2.08 KB | Source Code | 0 0
  1. import { get, set, isPlainObject, toPairs, fromPairs } from 'lodash'
  2.  
  3. interface ISerialized {
  4.   _type: string
  5.   data: unknown
  6. }
  7.  
  8. // Serialization
  9. function serialize(value: unknown): unknown {
  10.   if (value instanceof Map) {
  11.     return {
  12.       _type: 'Map',
  13.       data: toPairs(Array.from(value))
  14.     }
  15.   }
  16.  
  17.   if (value instanceof Set) {
  18.     return {
  19.       _type: 'Set',
  20.       data: Array.from(value).map(serialize)
  21.     }
  22.   }
  23.  
  24.   if (value instanceof Date) {
  25.     return {
  26.       _type: 'Date',
  27.       data: value.getTime()
  28.     }
  29.   }
  30.  
  31.   if (Array.isArray(value)) {
  32.     return value.map(serialize)
  33.   }
  34.  
  35.   if (isPlainObject(value)) {
  36.     const obj: Record<string, unknown> = {}
  37.     toPairs(value).forEach(([k, v]) => {
  38.       set(obj, k, serialize(v))
  39.     })
  40.     return obj
  41.   }
  42.  
  43.   return value
  44. }
  45.  
  46. // Deserialization
  47. function deserialize(value: unknown): unknown {
  48.   if (isPlainObject(value) && '_type' in value) {
  49.     const serializedValue = value as ISerialized
  50.     const type = serializedValue._type
  51.  
  52.     if (type === 'Map') {
  53.       return new Map(fromPairs(get(value, 'data') as Array<[string, unknown]>).map(([k, v]) => [k, deserialize(v)]))
  54.     }
  55.  
  56.     if (type === 'Set') {
  57.       return new Set((get(value, 'data') as Array<unknown>).map(deserialize))
  58.     }
  59.  
  60.     if (type === 'Date') {
  61.       return new Date(get(value, 'data') as number)
  62.     }
  63.  
  64.     return value
  65.   }
  66.  
  67.   if (Array.isArray(value)) {
  68.     return value.map(deserialize)
  69.   }
  70.  
  71.   if (isPlainObject(value)) {
  72.     const obj: Record<string, unknown> = {}
  73.     toPairs(value).forEach(([k, v]) => {
  74.       set(obj, k, deserialize(v))
  75.     })
  76.     return obj
  77.   }
  78.  
  79.   return value
  80. }
  81.  
  82. // Usage example:
  83. const data = {
  84.   a: new Map([["key", "value"], ["num1", "one"]]),
  85.   b: new Set([1, 2, 3]),
  86.   c: new Date(),
  87.   d: [1, 2, 3],
  88.   e: { f: "hello", g: [new Date(), new Set([1, 2, 3])] },
  89.   h: "a simple string",
  90.   i: 42,
  91.   j: true
  92. }
  93.  
  94. const serialized = JSON.stringify(serialize(data))
  95. console.log(serialized)
  96. const deserialized = deserialize(JSON.parse(serialized))
  97. console.log(deserialized)
  98.  
Tags: Serialize
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement