Source: collections/Comparer.js

  1. const { EqualityComparer } = require('./EqualityComparer');
  2. /**
  3. * @template T
  4. */
  5. class Comparer {
  6. /**
  7. * @param {EqualityComparer.<T>} [eqComparer] Optional. Defaults to
  8. * EqualityComparer.default. An EqualityComparer to use for comparing
  9. * two items. The method compareTo() returns 0 if the equality comparer
  10. * considers the two compared items to be equal.
  11. */
  12. constructor(eqComparer = EqualityComparer.default) {
  13. /** @type {EqualityComparer.<T>} */
  14. this._eqComparer = null;
  15. this.equalityComparer = eqComparer;
  16. };
  17. /**
  18. * @returns {EqualityComparer.<T>} The current EqualityComparer.
  19. */
  20. get equalityComparer() {
  21. return this._eqComparer;
  22. };
  23. /**
  24. * @access protected
  25. * @param {EqualityComparer.<T>} eqComparer The comparer
  26. * @returns {EqualityComparer.<T>} The same comparer that was given
  27. * @throws {Error} If the given value is not of type EqualityComparer.
  28. */
  29. _validateEqualityComparer(eqComparer) {
  30. if (!(eqComparer instanceof EqualityComparer)) {
  31. throw new Error(
  32. `The value provided is not of type ${EqualityComparer.name}: ${util.inspect(eqComparer)}`);
  33. }
  34. return eqComparer;
  35. };
  36. /**
  37. * @param {EqualityComparer.<T>} value An EqualityComparer to use.
  38. */
  39. set equalityComparer(value) {
  40. this._eqComparer = this._validateEqualityComparer(value);
  41. };
  42. /**
  43. * Compare two items and return a value that indicates which of them
  44. * is considered to be less or smaller. A negative value means that
  45. * x is smaller than y; 0 means they are equally large and a positive
  46. * value means that y is larger than x.
  47. *
  48. * @param {T} x
  49. * @param {T} y
  50. * @returns {Number} Returns either -1, 0 or 1.
  51. */
  52. compare(x, y) {
  53. throw new Error('Abstract method.');
  54. };
  55. };
  56. /**
  57. * @template T
  58. */
  59. class DefaultComparer extends Comparer {
  60. /**
  61. * Uses the instance of the EqualityComparer to determine whether two
  62. * items are considered to be equal.
  63. * @inheritDoc
  64. *
  65. * @param {T} x
  66. * @param {T} y
  67. * @returns {Number} Returns either -1, 0 or 1.
  68. */
  69. compare(x, y) {
  70. return this.equalityComparer.equals(x, y) ? 0 : (x < y ? -1 : 1);
  71. };
  72. };
  73. module.exports = Object.freeze({
  74. Comparer,
  75. DefaultComparer
  76. });