Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { get, set, isPlainObject, toPairs, fromPairs } from 'lodash'
- interface ISerialized {
- _type: string
- data: unknown
- }
- // Serialization
- function serialize(value: unknown): unknown {
- if (value instanceof Map) {
- return {
- _type: 'Map',
- data: toPairs(Array.from(value))
- }
- }
- if (value instanceof Set) {
- return {
- _type: 'Set',
- data: Array.from(value).map(serialize)
- }
- }
- if (value instanceof Date) {
- return {
- _type: 'Date',
- data: value.getTime()
- }
- }
- if (Array.isArray(value)) {
- return value.map(serialize)
- }
- if (isPlainObject(value)) {
- const obj: Record<string, unknown> = {}
- toPairs(value).forEach(([k, v]) => {
- set(obj, k, serialize(v))
- })
- return obj
- }
- return value
- }
- // Deserialization
- function deserialize(value: unknown): unknown {
- if (isPlainObject(value) && '_type' in value) {
- const serializedValue = value as ISerialized
- const type = serializedValue._type
- if (type === 'Map') {
- return new Map(fromPairs(get(value, 'data') as Array<[string, unknown]>).map(([k, v]) => [k, deserialize(v)]))
- }
- if (type === 'Set') {
- return new Set((get(value, 'data') as Array<unknown>).map(deserialize))
- }
- if (type === 'Date') {
- return new Date(get(value, 'data') as number)
- }
- return value
- }
- if (Array.isArray(value)) {
- return value.map(deserialize)
- }
- if (isPlainObject(value)) {
- const obj: Record<string, unknown> = {}
- toPairs(value).forEach(([k, v]) => {
- set(obj, k, deserialize(v))
- })
- return obj
- }
- return value
- }
- // Usage example:
- const data = {
- a: new Map([["key", "value"], ["num1", "one"]]),
- b: new Set([1, 2, 3]),
- c: new Date(),
- d: [1, 2, 3],
- e: { f: "hello", g: [new Date(), new Set([1, 2, 3])] },
- h: "a simple string",
- i: 42,
- j: true
- }
- const serialized = JSON.stringify(serialize(data))
- console.log(serialized)
- const deserialized = deserialize(JSON.parse(serialized))
- console.log(deserialized)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement