Guest User

Untitled

a guest
Feb 17th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. /**
  2. * Checks the type of the specified value.
  3. *
  4. * @example checkType(Number, 4)
  5. * @example checkType(String, 'hi')
  6. * @example checkType(String, 4) // throws
  7. * @example checkType({ // custom checker
  8. * checkType (value, checkType) {
  9. * checkType(Number, value)
  10. * }
  11. * }, 4)
  12. */
  13. function checkType (type, value) {
  14. if (type === String && (typeof value !== 'string' || !(value instanceof String))) {
  15. throw new Error('Expected string.')
  16. } else if (type === Number && (typeof value !== 'number' || !(value instanceof Number))) {
  17. throw new Error('Expected number')
  18. } else if (type === Boolean && (typeof value !== 'boolean' || !(value instanceof Boolean))) {
  19. throw new Error('Expected boolean.')
  20. } else if (type === Date && !(value instanceof Date)) {
  21. throw new Error('Expected Date.')
  22. } else if (type === RegExp && !(value instanceof RegExp)) {
  23. throw new Error('Expected RegExp.')
  24. } else if (typeof type.checkType === 'function') {
  25. type.checkType(value, checkType)
  26. } else if (!(value instanceof type)) {
  27. throw new Error('Expected ' + type.name + '.')
  28. }
  29. }
Add Comment
Please, Sign In to add comment