Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. const isString = require('is-string')
  2. const isNumber = require('is-number')
  3.  
  4. const parseBoolean = (string, defaultValue = null) => {
  5. // handle booleans & numbers
  6. if (!isString(string)) {
  7. return !!string
  8. }
  9.  
  10. // handle numbers/number-strings
  11. if (isNumber(string)) {
  12. return !!parseFloat(string)
  13. }
  14.  
  15. // handle strings
  16. switch (string.trim().toLowerCase()) {
  17. case 'true': return true
  18. case 'false': return false
  19. case 'yes': return true
  20. case 'no': return false
  21. default: return defaultValue
  22. }
  23. }
  24.  
  25. module.exports = parseBoolean
  26.  
  27. // "true" = true
  28. // "false" = false
  29. // "True" = true
  30. // "False" = false
  31. // "TRUE" = true
  32. // "FALSE" = false
  33. // "yes" = true
  34. // "no" = false
  35. // "Yes" = true
  36. // "No" = false
  37. // "YES" = true
  38. // "NO" = false
  39. // true = true
  40. // false = false
  41. // 1 = true
  42. // -1 = false
  43. // 0 = false
  44. // 2 = true
  45. // "1" = true
  46. // "-1" = false
  47. // "0" = false
  48. // "2" = true
  49. // [] = true
  50. // {} = true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement