jumpstorm/engine/utils/coding.ts

28 lines
578 B
TypeScript
Raw Normal View History

2023-08-23 21:44:59 -04:00
const replacer = (_key: any, value: any) => {
if (value instanceof Map) {
return {
2023-08-25 18:48:17 -04:00
dataType: 'Map',
value: Array.from(value.entries())
2023-08-23 21:44:59 -04:00
};
} else {
return value;
}
};
const reviver = (_key: any, value: any) => {
2023-08-25 18:48:17 -04:00
if (typeof value === 'object' && value !== null) {
if (value.dataType === 'Map') {
2023-08-23 21:44:59 -04:00
return new Map(value.value);
}
}
return value;
};
export const stringify = (obj: any) => {
return JSON.stringify(obj, replacer);
};
export const parse = <T>(str: string) => {
return JSON.parse(str, reviver) as unknown as T;
};