Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * @param variable The variable you want to get the type of
- * @returns 'string', 'number', 'array', 'function', or 'object'
- */
- function type (variable) {
- return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase()
- }
- /**
- * Checks if a variable matches the expected format at every level. This includes checking that any given object has the
- * same keys as expectedFormat.
- * @param variable The variable to check
- * @param expectedFormat 'string', 'number', 'function', or javascript object/array that contains any of these items.
- * Example expected object: {
- * shoppingList: [
- * {
- * name: 'string',
- * quantity: 'number'
- * }
- * ],
- * friendNames: ['string']
- * }
- * @returns boolean true if variable matches the expected format, false otherwise
- */
- function valid (variable, expectedFormat) {
- switch (type(variable)) {
- case 'object':
- if (
- type(expectedFormat) !== 'object' ||
- !Object.keys(expectedFormat).every(prop => variable.hasOwnProperty(prop))
- ) {
- return false
- }
- return Object.keys(expectedFormat).every(key => valid(variable[key], expectedFormat[key]))
- case 'array':
- if (type(expectedFormat) !== 'array') {
- return false
- }
- return variable.every(item => valid(item, expectedFormat[0]))
- case 'string':
- return expectedFormat === 'string'
- case 'number':
- return expectedFormat === 'number'
- case 'function':
- return expectedFormat === 'function'
- default:
- console.log(`UnexpectedFormat type '${type(expectedFormat)}'`)
- return false // Unexpected type
- }
- }
Add Comment
Please, Sign In to add comment