Last active
November 7, 2018 13:09
-
-
Save mividtim/97db63bda3484d9629b496df0f2ce200 to your computer and use it in GitHub Desktop.
Flow type definition (libdef) for Json, and ToJson which drops non-serializable props
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
// Flow type definition for Json (lower-case so as not to collide with JSON) | |
// ToJson function accepts any JS variable and sets any non-serializable | |
// vars or properties on objects to null | |
// The author has found this quite useful for logging complex objects safely | |
export type JsonPrimitive = null | string | number | boolean; | |
export type JsonObject = { [string]: Json }; | |
export type JsonArray = Json[]; | |
export type Json = JsonPrimitive | JsonObject | JsonArray; | |
export function isPrimitive(value: any): boolean { | |
return value === null || ['string', 'number', 'boolean'].includes(value); | |
} | |
export function ArrayToJson(array: any[]): JsonArray { | |
return array.reduce( | |
(json: JsonArray, value: any): JsonArray => { | |
return Array.isArray(json) | |
? [...json, ToJson(value)] | |
: [ToJson(value)]; | |
}, | |
); | |
} | |
export function ObjectToJson(object: Object): JsonObject { | |
return Object.keys(object).reduce( | |
(json: JsonObject, key: string): JsonObject => { | |
return typeof json === 'object' | |
&& !Array.isArray(json) | |
? { ...json, [key]: ToJson(object[key]) } | |
: { [key]: ToJson(object[key]) }; | |
}, | |
{}, | |
); | |
} | |
export function ToJson(value: any): Json { | |
return isPrimitive(value) ? value | |
: Array.isArray(value) ? ArrayToJson(value) | |
: typeof value === 'object' ? ObjectToJson(value) | |
: null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment