Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const isString = require('is-string')
- const isNumber = require('is-number')
- const parseBoolean = (string, defaultValue = null) => {
- // handle booleans & numbers
- if (!isString(string)) {
- return !!string
- }
- // handle numbers/number-strings
- if (isNumber(string)) {
- return !!parseFloat(string)
- }
- // handle strings
- switch (string.trim().toLowerCase()) {
- case 'true': return true
- case 'false': return false
- case 'yes': return true
- case 'no': return false
- default: return defaultValue
- }
- }
- module.exports = parseBoolean
- // "true" = true
- // "false" = false
- // "True" = true
- // "False" = false
- // "TRUE" = true
- // "FALSE" = false
- // "yes" = true
- // "no" = false
- // "Yes" = true
- // "No" = false
- // "YES" = true
- // "NO" = false
- // true = true
- // false = false
- // 1 = true
- // -1 = false
- // 0 = false
- // 2 = true
- // "1" = true
- // "-1" = false
- // "0" = false
- // "2" = true
- // [] = true
- // {} = true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement