utils.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * The MIT License (MIT)
  3. * Copyright (c) 2017-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
  4. */
  5. 'use strict';
  6. /**
  7. * Flattens a nested disjunction node to a list.
  8. *
  9. * /a|b|c|d/
  10. *
  11. * {{{a, b}, c}, d} -> [a, b, c, d]
  12. */
  13. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  14. function disjunctionToList(node) {
  15. if (node.type !== 'Disjunction') {
  16. throw new TypeError('Expected "Disjunction" node, got "' + node.type + '"');
  17. }
  18. var list = [];
  19. if (node.left && node.left.type === 'Disjunction') {
  20. list.push.apply(list, _toConsumableArray(disjunctionToList(node.left)).concat([node.right]));
  21. } else {
  22. list.push(node.left, node.right);
  23. }
  24. return list;
  25. }
  26. /**
  27. * Builds a nested disjunction node from a list.
  28. *
  29. * /a|b|c|d/
  30. *
  31. * [a, b, c, d] -> {{{a, b}, c}, d}
  32. */
  33. function listToDisjunction(list) {
  34. return list.reduce(function (left, right) {
  35. return {
  36. type: 'Disjunction',
  37. left: left,
  38. right: right
  39. };
  40. });
  41. }
  42. /**
  43. * Increases a quantifier by one.
  44. * Does not change greediness.
  45. * * -> +
  46. * + -> {2,}
  47. * ? -> {1,2}
  48. * {2} -> {3}
  49. * {2,} -> {3,}
  50. * {2,3} -> {3,4}
  51. */
  52. function increaseQuantifierByOne(quantifier) {
  53. if (quantifier.kind === '*') {
  54. quantifier.kind = '+';
  55. } else if (quantifier.kind === '+') {
  56. quantifier.kind = 'Range';
  57. quantifier.from = 2;
  58. delete quantifier.to;
  59. } else if (quantifier.kind === '?') {
  60. quantifier.kind = 'Range';
  61. quantifier.from = 1;
  62. quantifier.to = 2;
  63. } else if (quantifier.kind === 'Range') {
  64. quantifier.from += 1;
  65. if (quantifier.to) {
  66. quantifier.to += 1;
  67. }
  68. }
  69. }
  70. module.exports = {
  71. disjunctionToList: disjunctionToList,
  72. listToDisjunction: listToDisjunction,
  73. increaseQuantifierByOne: increaseQuantifierByOne
  74. };