toBoolean.js 668 B

1234567891011121314151617181920
  1. var trim = require('./trim');
  2. function boolMatch(s, matchers) {
  3. var i, matcher, down = s.toLowerCase();
  4. matchers = [].concat(matchers);
  5. for (i = 0; i < matchers.length; i += 1) {
  6. matcher = matchers[i];
  7. if (!matcher) continue;
  8. if (matcher.test && matcher.test(s)) return true;
  9. if (matcher.toLowerCase() === down) return true;
  10. }
  11. }
  12. module.exports = function toBoolean(str, trueValues, falseValues) {
  13. if (typeof str === 'number') str = '' + str;
  14. if (typeof str !== 'string') return !!str;
  15. str = trim(str);
  16. if (boolMatch(str, trueValues || ['true', '1'])) return true;
  17. if (boolMatch(str, falseValues || ['false', '0'])) return false;
  18. };