Guest User

Untitled

a guest
Dec 12th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. /*
  2. * @param variable The variable you want to get the type of
  3. * @returns 'string', 'number', 'array', 'function', or 'object'
  4. */
  5. function type (variable) {
  6. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase()
  7. }
  8.  
  9. /**
  10. * Checks if a variable matches the expected format at every level. This includes checking that any given object has the
  11. * same keys as expectedFormat.
  12. * @param variable The variable to check
  13. * @param expectedFormat 'string', 'number', 'function', or javascript object/array that contains any of these items.
  14. * Example expected object: {
  15. * shoppingList: [
  16. * {
  17. * name: 'string',
  18. * quantity: 'number'
  19. * }
  20. * ],
  21. * friendNames: ['string']
  22. * }
  23. * @returns boolean true if variable matches the expected format, false otherwise
  24. */
  25. function valid (variable, expectedFormat) {
  26. switch (type(variable)) {
  27. case 'object':
  28. if (
  29. type(expectedFormat) !== 'object' ||
  30. !Object.keys(expectedFormat).every(prop => variable.hasOwnProperty(prop))
  31. ) {
  32. return false
  33. }
  34. return Object.keys(expectedFormat).every(key => valid(variable[key], expectedFormat[key]))
  35.  
  36. case 'array':
  37. if (type(expectedFormat) !== 'array') {
  38. return false
  39. }
  40. return variable.every(item => valid(item, expectedFormat[0]))
  41.  
  42. case 'string':
  43. return expectedFormat === 'string'
  44.  
  45. case 'number':
  46. return expectedFormat === 'number'
  47.  
  48. case 'function':
  49. return expectedFormat === 'function'
  50.  
  51. default:
  52. console.log(`UnexpectedFormat type '${type(expectedFormat)}'`)
  53. return false // Unexpected type
  54. }
  55. }
Add Comment
Please, Sign In to add comment