c35c89189ee54922446b5e2d0086463c98011e5c5a9afcb57d45479f8d7f82cfacd453b49b9779858ac10b40a90d1c83f021d2056fe334d6070aabe3fc2a7f-exec 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. 'use strict';
  2. const Hoek = require('@hapi/hoek');
  3. const Any = require('../any');
  4. const internals = {
  5. Set: require('../../set')
  6. };
  7. internals.Boolean = class extends Any {
  8. constructor() {
  9. super();
  10. this._type = 'boolean';
  11. this._flags.insensitive = true;
  12. this._inner.truthySet = new internals.Set();
  13. this._inner.falsySet = new internals.Set();
  14. }
  15. _base(value, state, options) {
  16. const result = {
  17. value
  18. };
  19. if (typeof value === 'string' &&
  20. options.convert) {
  21. const normalized = this._flags.insensitive ? value.toLowerCase() : value;
  22. result.value = (normalized === 'true' ? true
  23. : (normalized === 'false' ? false : value));
  24. }
  25. if (typeof result.value !== 'boolean') {
  26. result.value = (this._inner.truthySet.has(value, null, null, this._flags.insensitive) ? true
  27. : (this._inner.falsySet.has(value, null, null, this._flags.insensitive) ? false : value));
  28. }
  29. result.errors = (typeof result.value === 'boolean') ? null : this.createError('boolean.base', { value }, state, options);
  30. return result;
  31. }
  32. truthy(...values) {
  33. const obj = this.clone();
  34. values = Hoek.flatten(values);
  35. for (let i = 0; i < values.length; ++i) {
  36. const value = values[i];
  37. Hoek.assert(value !== undefined, 'Cannot call truthy with undefined');
  38. obj._inner.truthySet.add(value);
  39. }
  40. return obj;
  41. }
  42. falsy(...values) {
  43. const obj = this.clone();
  44. values = Hoek.flatten(values);
  45. for (let i = 0; i < values.length; ++i) {
  46. const value = values[i];
  47. Hoek.assert(value !== undefined, 'Cannot call falsy with undefined');
  48. obj._inner.falsySet.add(value);
  49. }
  50. return obj;
  51. }
  52. insensitive(enabled) {
  53. const insensitive = enabled === undefined ? true : !!enabled;
  54. if (this._flags.insensitive === insensitive) {
  55. return this;
  56. }
  57. const obj = this.clone();
  58. obj._flags.insensitive = insensitive;
  59. return obj;
  60. }
  61. describe() {
  62. const description = super.describe();
  63. description.truthy = [true, ...this._inner.truthySet.values()];
  64. description.falsy = [false, ...this._inner.falsySet.values()];
  65. return description;
  66. }
  67. };
  68. module.exports = new internals.Boolean();