Skip to content

Instantly share code, notes, and snippets.

@prmichaelsen
Last active November 11, 2023 01:37
Show Gist options
  • Save prmichaelsen/c6bf619a7fd96a30d2b6cb9ff93aaca4 to your computer and use it in GitHub Desktop.
Save prmichaelsen/c6bf619a7fd96a30d2b6cb9ff93aaca4 to your computer and use it in GitHub Desktop.
export type O<T> = { [key: string]: T };
export type NonObject = undefined | null | boolean | string | number | ((...args: any[]) => any);
import { NonObject } from "./core-types";
export type DeepComplete<T> = T extends NonObject
? Exclude<T, undefined>
: T extends Array<infer U>
? DeepCompleteArray<U>
: T extends Map<infer K, infer V>
? DeepCompleteMap<K, V>
: DeepCompleteObject<T>;
export type DeepCompleteArray<T> = Array<DeepComplete<T>>;
export type DeepCompleteMap<K, V> = Map<DeepComplete<K>, DeepComplete<V>>;
export type DeepCompleteObject<T> = {
[K in keyof T]-?: DeepComplete<T[K]>;
};
// Example usage
const b = {
hi: undefined,
bye: 'cool',
};
type B = typeof b;
type CompleteB = DeepComplete<B>;
// Now CompleteB is { bye: 'cool' }
export function jsonDeserializeHelper(serializedValue: any) {
const { type, value } = serializedValue;
if (type === 'number') {
if (value === 'NaN') {
return NaN;
} else if (value === 'Infinity') {
return Infinity;
} else if (value === '-Infinity') {
return -Infinity;
}
// Handle other number types if needed
} else if (type === 'bigint') {
return BigInt(value);
} else if (type === 'symbol') {
const msg = `[ERROR]: Symbols are not supported by the json-deserializer-helper. Symbols are often used for internal purposes within an application. Serializing and deserializing them might not have a meaningful use case in most scenarios.`;
const err = new Error(msg);
console.log(err);
throw err;
} else if (type === 'function') {
const msg = `[ERROR]: Serializing functions is discouraged due to potential behavior inconsistencies, security risks, cross-environment compatibility issues, and the complexity of maintaining and debugging serialized code.`;
const err = new Error(msg);
console.log(err);
throw err;
}
return value;
}
import { jsonSerializeHelper } from "./json-serialize-helper";
import { DeepComplete } from "ui";
/**
* recursively traverses the object and returns a new
* object with no undefined keys.
* keeps falsey or empty values, but never undefined
*/
export function serialize<T>(_o: T): DeepComplete<T> {
const o = _o as any;
const result: any = {};
Object.keys(o).forEach(key => {
const value = o[key];
if (value === undefined) {
return;
}
if (
value !== null
&& typeof value !== 'undefined'
&& typeof value !== 'string'
&& typeof value !== 'boolean'
&& typeof value !== 'number'
&& typeof value !== 'function'
&& !Array.isArray(value)
) {
result[key] = serialize(value);
} else {
result[key] = jsonSerializeHelper(value);
}
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment