Skip to content

Instantly share code, notes, and snippets.

@Nick-Gabe
Last active January 2, 2023 14:30
Show Gist options
  • Save Nick-Gabe/ea01e3a8826ab5fba0e5c0bd6af687b5 to your computer and use it in GitHub Desktop.
Save Nick-Gabe/ea01e3a8826ab5fba0e5c0bd6af687b5 to your computer and use it in GitHub Desktop.
Validate types of an object or value based on expected result.
function validateType(expected, input) {
if (!input) return false;
// maps verifications for standard types and custom classes
const typeVerifier = {
Object: (x) => typeof x === 'object' &&
!Array.isArray(x) &&
x !== null,
String: (x) => typeof x === 'string',
Number: (x) => typeof x === 'number',
BigInt: (x) => typeof x === 'bigint',
Boolean: (x) => typeof x === 'boolean',
Array: (x) => Array.isArray(x),
Date: (x) => x instanceof Date,
fallback: (x, customClass) => x instanceof customClass
}
const getFunctionName = (fn) => fn
.toString()
.match(/\w*(?=\(|\{|])/)[0];
// checks if expected type is standard or custom, and runs functions accordingly
const matchesExpected = (expected, input) => {
const typeName = getFunctionName(expected);
const standardType = typeVerifier[typeName];
if (typeName === 'Object') {
const hasNoProps = expected === Object || Object.keys(expected).length === 0;
return hasNoProps ? typeVerifier.Object(input) : validateType(expected, input)
}
return standardType ? standardType(input) : typeVerifier.fallback(input, expected);
}
// if expected isn't an object, just verify it
if (!typeVerifier.Object(expected)) {
return matchesExpected(expected, input)
}
// if it is an object, run a recursive verification
return Object
.entries(expected)
.every(([key, type]) => {
const value = input[key];
const expectedScope = expected[key];
return matchesExpected(expectedScope, value)
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment