-
-
Save GuiMarthe/3219e2b51323e5326cb43cec1892fe48 to your computer and use it in GitHub Desktop.
Validate types of an object or value based on expected result.
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
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