option-parser.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Options parser for custom tag
  3. */
  4. class OptionParser {
  5. /**
  6. * @typedef ParseRangeResult
  7. * @property {number} start - start index
  8. * @property {number} end - end index
  9. */
  10. /**
  11. * Parse range expression
  12. *
  13. * <ul>
  14. * <li>ex:</li>
  15. * <ul>
  16. * <li>1:2 -> { start: 1, end: 2 }</li>
  17. * <li>1: -> { start: 1, end: -1 }</li>
  18. * <li>2+3 -> { start: 1, end: 5 }</li>
  19. * </ul>
  20. * </ul>
  21. *
  22. * @see https://regex101.com/r/w4KCwC/4
  23. *
  24. * @static
  25. * @param {string} str
  26. * @returns {ParseRangeResult}
  27. */
  28. static parseRange(str) {
  29. if (str == null) {
  30. return null;
  31. }
  32. // see: https://regex101.com/r/w4KCwC/4
  33. const match = str.match(/^(-?[0-9]+)(([:+]{1})(-?[0-9]+)?)?$/);
  34. if (!match) {
  35. return null;
  36. }
  37. // determine start
  38. let start;
  39. let end;
  40. // has operator
  41. if (match[3] != null) {
  42. start = +match[1];
  43. const operator = match[3];
  44. // determine end
  45. if (operator === ':') {
  46. end = +match[4] || -1; // set last(-1) if undefined
  47. }
  48. else if (operator === '+') {
  49. end = +match[4] || 0; // plus zero if undefined
  50. end += start;
  51. }
  52. }
  53. // don't have operator
  54. else {
  55. start = 1;
  56. end = +match[1];
  57. }
  58. return { start, end };
  59. }
  60. }
  61. module.exports = OptionParser;