boolean.js 860 B

1234567891011121314151617181920212223242526272829303132
  1. 'use strict';
  2. const CastError = require('../error/cast');
  3. /*!
  4. * Given a value, cast it to a boolean, or throw a `CastError` if the value
  5. * cannot be casted. `null` and `undefined` are considered valid.
  6. *
  7. * @param {Any} value
  8. * @param {String} [path] optional the path to set on the CastError
  9. * @return {Boolean|null|undefined}
  10. * @throws {CastError} if `value` is not one of the allowed values
  11. * @api private
  12. */
  13. module.exports = function castBoolean(value, path) {
  14. if (module.exports.convertToTrue.has(value)) {
  15. return true;
  16. }
  17. if (module.exports.convertToFalse.has(value)) {
  18. return false;
  19. }
  20. if (value == null) {
  21. return value;
  22. }
  23. throw new CastError('boolean', value, path);
  24. };
  25. module.exports.convertToTrue = new Set([true, 'true', 1, '1', 'yes']);
  26. module.exports.convertToFalse = new Set([false, 'false', 0, '0', 'no']);