empty-values-service.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import {DataType} from './data-type.js';
  2. import {Errorf} from '@e22m4u/js-format';
  3. import {Service} from '@e22m4u/js-service';
  4. import {isDeepEqual} from './utils/index.js';
  5. import {getDataTypeOf} from './utils/index.js';
  6. /**
  7. * Empty values service.
  8. */
  9. export class EmptyValuesService extends Service {
  10. /**
  11. * Empty values map.
  12. *
  13. * @type {Map<string, *[]>}
  14. */
  15. _emptyValuesMap = new Map([
  16. [DataType.ANY, [undefined, null]],
  17. [DataType.STRING, [undefined, null, '']],
  18. [DataType.NUMBER, [undefined, null, 0]],
  19. [DataType.BOOLEAN, [undefined, null]],
  20. [DataType.ARRAY, [undefined, null, []]],
  21. [DataType.OBJECT, [undefined, null, {}]],
  22. ]);
  23. /**
  24. * Set empty values of data type.
  25. *
  26. * @param {string} dataType
  27. * @param {*[]} emptyValues
  28. * @returns {EmptyValuesService}
  29. */
  30. setEmptyValuesOf(dataType, emptyValues) {
  31. if (!Object.values(DataType).includes(dataType))
  32. throw new Errorf(
  33. 'The argument "dataType" of the EmptyValuesService.setEmptyValuesOf ' +
  34. 'must be one of data types: %l, but %v given.',
  35. Object.values(DataType),
  36. dataType,
  37. );
  38. if (!Array.isArray(emptyValues))
  39. throw new Errorf(
  40. 'The argument "emptyValues" of the EmptyValuesService.setEmptyValuesOf ' +
  41. 'must be an Array, but %v given.',
  42. emptyValues,
  43. );
  44. this._emptyValuesMap.set(dataType, emptyValues);
  45. return this;
  46. }
  47. /**
  48. * Is empty.
  49. *
  50. * @param {*} value
  51. * @returns {boolean}
  52. */
  53. isEmpty(value) {
  54. const dataType = getDataTypeOf(value);
  55. return this._emptyValuesMap.get(dataType).some(v => isDeepEqual(v, value));
  56. }
  57. /**
  58. * Is empty for type.
  59. *
  60. * @param {string} dataType
  61. * @param {*} value
  62. * @returns {boolean}
  63. */
  64. isEmptyByType(dataType, value) {
  65. if (!Object.values(DataType).includes(dataType))
  66. throw new Errorf(
  67. 'The argument "dataType" of EmptyValuesService.isEmptyByType ' +
  68. 'must be one of data types: %l, but %v given.',
  69. Object.values(DataType),
  70. dataType,
  71. );
  72. return this._emptyValuesMap.get(dataType).some(v => isDeepEqual(v, value));
  73. }
  74. }