Created
April 11, 2019 22:48
-
-
Save konsumer/383c0e430679e3268788f13da7721aed to your computer and use it in GitHub Desktop.
Similar to parse-boolean, to turn a string into a boolean, but it permits numbers, actual booleans, number-strings, and yes|no|true|false strings (case-insensitive, even with padding.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment