Skip to content

Instantly share code, notes, and snippets.

@donnaken15
Last active October 11, 2023 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donnaken15/17f5a7a6d0a029c6cf4a37bbe013a31d to your computer and use it in GitHub Desktop.
Save donnaken15/17f5a7a6d0a029c6cf4a37bbe013a31d to your computer and use it in GitHub Desktop.
object type checking with recursion
// checks if an object's data is symmetric with a struct with defining types
function typecheck(object, types, optional=null) {
// TODO: optional error print, showing
// where in the object did this function fail
// if that's even possible
//
// example:
// typecheck({
// "thing": 1,
// "thing2": "2",
// "thing3": {
// "thing4": [ "4", -4, 4 ],
// "thing5": {
// "param": {
// "within_another": 4
// }
// }
// }
// }, {
// "thing": "number",
// "thing2": "string",
// "thing3": {
// "thing4": [ "*" ],
// "thing5": {
// "param": {
// "within_another": "number"
// }
// }
// }
// });
//
'use strict';
if (Array.isArray(types))
{
// `types` at this point must contain a singular element that has
// the type string to match the type of the elements inside the object
// i.e. [ 0, 1, 2, 3 ] == [ 'number' ]
//
// use [ '*' ] to contain elements of any type
if (Array.isArray(object)) {
if (types.length === 1) {
// support alternating types with modulo?
// (like ['number', 'string', 'number'])
if (types[0] === '*') return true;
for (var i = 0; i < object.length; i++)
if (!typecheck(object[i], types[0]))
return false;
return true;
}
else
throw "Type object "+JSON.stringify(types)+
"is an invalid array to test against "+JSON.stringify(object);
}
} else if (types.toString() === '[object Object]') {
var all_keys = [...new Set([...Object.keys(object), ...Object.keys(types)])];
for (var i = 0; i < all_keys.length; i++) {
var o = all_keys[i];
if (!types.hasOwnProperty(o))
return false;
if (!object.hasOwnProperty(o) && !(optional === null || !optional[o]))
continue; // skip if optional item not in object
if (!typecheck(object[o], types[o],
optional !== null && optional.hasOwnProperty(o) ? optional[o] : null))
return false;
}
return true;
}
return typeof object === types.toString() || types === "*";
// if type = 'object', any type of struct
// is accepted, or allow anything if = '*'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment