boolean.js 859 B

12345678910111213141516171819202122232425262728293031
  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 (value == null) {
  15. return value;
  16. }
  17. if (module.exports.convertToTrue.has(value)) {
  18. return true;
  19. }
  20. if (module.exports.convertToFalse.has(value)) {
  21. return false;
  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']);