Skip to content

Instantly share code, notes, and snippets.

@krohne
Forked from CMCDragonkai/parseBooleanStyle.js
Last active August 29, 2015 14:15
Show Gist options
  • Save krohne/105530d30e1e41919edc to your computer and use it in GitHub Desktop.
Save krohne/105530d30e1e41919edc to your computer and use it in GitHub Desktop.
/**
* Parses mixed type values into booleans. This is the same function as filter_var in PHP using boolean validation
* @param {Mixed} value
* @param {Boolean} nullOnFailure = false
* @return {Boolean|Null}
*/
var parseBooleanStyle = function(value, nullOnFailure = false){
if (typeof value !== 'string')
return Boolean(value);
switch(value.toLowerCase()){
case 'true':
case '1':
case 'on':
case 'yes':
case 'y':
value = true;
break;
case 'false':
case '0':
case 'off':
case 'no':
case 'n':
case '':
value = false;
break;
default:
if(nullOnFailure){
value = null;
}else{
value = false;
}
break;
}
return value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment