range.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. const _ = require("lodash");
  3. function stringifyRangeBound(bound) {
  4. if (bound === null) {
  5. return "";
  6. }
  7. if (bound === Infinity || bound === -Infinity) {
  8. return bound.toString().toLowerCase();
  9. }
  10. return JSON.stringify(bound);
  11. }
  12. function parseRangeBound(bound, parseType) {
  13. if (!bound) {
  14. return null;
  15. }
  16. if (bound === "infinity") {
  17. return Infinity;
  18. }
  19. if (bound === "-infinity") {
  20. return -Infinity;
  21. }
  22. return parseType(bound);
  23. }
  24. function stringify(data) {
  25. if (data === null)
  26. return null;
  27. if (!Array.isArray(data))
  28. throw new Error("range must be an array");
  29. if (!data.length)
  30. return "empty";
  31. if (data.length !== 2)
  32. throw new Error("range array length must be 0 (empty) or 2 (lower and upper bounds)");
  33. if (Object.prototype.hasOwnProperty.call(data, "inclusive")) {
  34. if (data.inclusive === false)
  35. data.inclusive = [false, false];
  36. else if (!data.inclusive)
  37. data.inclusive = [true, false];
  38. else if (data.inclusive === true)
  39. data.inclusive = [true, true];
  40. } else {
  41. data.inclusive = [true, false];
  42. }
  43. _.each(data, (value, index) => {
  44. if (_.isObject(value)) {
  45. if (Object.prototype.hasOwnProperty.call(value, "inclusive"))
  46. data.inclusive[index] = !!value.inclusive;
  47. if (Object.prototype.hasOwnProperty.call(value, "value"))
  48. data[index] = value.value;
  49. }
  50. });
  51. const lowerBound = stringifyRangeBound(data[0]);
  52. const upperBound = stringifyRangeBound(data[1]);
  53. return `${(data.inclusive[0] ? "[" : "(") + lowerBound},${upperBound}${data.inclusive[1] ? "]" : ")"}`;
  54. }
  55. exports.stringify = stringify;
  56. function parse(value, parser) {
  57. if (value === null)
  58. return null;
  59. if (value === "empty") {
  60. return [];
  61. }
  62. let result = value.substring(1, value.length - 1).split(",", 2);
  63. if (result.length !== 2)
  64. return value;
  65. result = result.map((item, index) => {
  66. return {
  67. value: parseRangeBound(item, parser),
  68. inclusive: index === 0 ? value[0] === "[" : value[value.length - 1] === "]"
  69. };
  70. });
  71. return result;
  72. }
  73. exports.parse = parse;
  74. //# sourceMappingURL=range.js.map