Skip to content

Instantly share code, notes, and snippets.

@Sequoya42
Last active June 15, 2018 17:01
Show Gist options
  • Save Sequoya42/1047b0625401a45050c314e654d69663 to your computer and use it in GitHub Desktop.
Save Sequoya42/1047b0625401a45050c314e654d69663 to your computer and use it in GitHub Desktop.
function makeSchema(x) {
if (Array.isArray(x)) return x.map(k => makeSchema(k));
else if (typeof x === 'boolean') return true;
else if (typeof x === 'number') return 1;
else if (typeof x === 'string') return 'string';
else if (typeof x === 'object') {
let obj = {};
for (let k in x) {
obj[k] = makeSchema(x[k]);
}
return obj;
}
}
@Raphy42
Copy link

Raphy42 commented Jun 15, 2018

wesh

function makeBetterSchema(x) {
  switch (typeof x) {
    case 'boolean': return true
    case 'number': return 1
    case 'string': return 'string'
    case 'object': {
      return Array.isArray(x)
        ? x.map(makeBetterSchema)
        : Object.keys(x).reduce((acc, k) => ({ ...acc, [k]: makeBetterSchema(x[k])}), {})
    }
  }
}

@Sequoya42
Copy link
Author

Sequoya42 commented Jun 15, 2018

Wesh

function makeSchema(x) {
  if (Array.isArray(x)) {
    x = x.map(k => makeSchema(k));
    if (!x.some(e => e !== 'string')) x = ['string'];
    return x;
  } else {
    let type = typeof x;
    if (type === 'boolean') return true;
    else if (type === 'number') return 1;
    else if (type === 'string') return 'string';
    let obj = {};
    for (let k in x) {
      obj[k] = makeSchema(x[k]);
    }
    return obj;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment