Skip to content

Instantly share code, notes, and snippets.

@mrclay
Created March 4, 2025 02:24
Show Gist options
  • Select an option

  • Save mrclay/34e9705e262e007ec64ab59fe7faa582 to your computer and use it in GitHub Desktop.

Select an option

Save mrclay/34e9705e262e007ec64ab59fe7faa582 to your computer and use it in GitHub Desktop.

Revisions

  1. mrclay created this gist Mar 4, 2025.
    45 changes: 45 additions & 0 deletions buildSchema.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    /**
    * Return an object that describes types of the given value.
    *
    * @param {unknown} value
    * @param {object} schema
    */
    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;
    }