Created
August 13, 2025 19:53
-
-
Save mrclay/5c5f687232982d9e04fcc1fabe61b8e1 to your computer and use it in GitHub Desktop.
Simple script to describe a bunch of array elements
This file contains hidden or 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
| /** | |
| * Return an object that describes types of the given value. This can be used to | |
| * analyze an array of objects and return something that describes them. | |
| * | |
| * const schema = buildSchema(elements); | |
| * | |
| * @param {unknown} value | |
| * @param {object} schema (used for recursion) | |
| */ | |
| export function buildSchema(value, schema = {}) { | |
| if (value === null) { | |
| schema.nulls = (schema.nulls || 0) + 1; | |
| return schema; | |
| } | |
| if (typeof value === 'string') { | |
| schema.strings = (schema.strings || 0) + 1; | |
| return schema; | |
| } | |
| if (typeof value === 'number') { | |
| schema.numbers = (schema.numbers || 0) + 1; | |
| return schema; | |
| } | |
| if (Array.isArray(value)) { | |
| schema.arrayOf = schema.arrayOf || {}; | |
| value.forEach(el => buildSchema(el, schema.arrayOf)); | |
| return schema; | |
| } | |
| if (typeof value === 'object') { | |
| schema.obj = schema.obj || {}; | |
| for (const [k2, v2] of Object.entries(value)) { | |
| schema.obj[k2] = schema.obj[k2] || {}; | |
| buildSchema(v2, schema.obj[k2]); | |
| } | |
| // Check for missing properties that the schema knows about. | |
| for (const k3 of Object.keys(schema.obj)) { | |
| if (!Object.hasOwn(value, k3)) { | |
| schema.obj[k3].undefineds = (schema.obj[k3].undefineds || 0) + 1; | |
| } | |
| } | |
| } | |
| return schema; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment