disjunction-remove-duplicates-transform.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * The MIT License (MIT)
  3. * Copyright (c) 2017-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
  4. */
  5. 'use strict';
  6. var NodePath = require('../../traverse/node-path');
  7. var _require = require('../../transform/utils'),
  8. disjunctionToList = _require.disjunctionToList,
  9. listToDisjunction = _require.listToDisjunction;
  10. /**
  11. * Removes duplicates from a disjunction sequence:
  12. *
  13. * /(ab|bc|ab)+(xy|xy)+/ -> /(ab|bc)+(xy)+/
  14. */
  15. module.exports = {
  16. Disjunction: function Disjunction(path) {
  17. var node = path.node;
  18. // Make unique nodes.
  19. var uniqueNodesMap = {};
  20. var parts = disjunctionToList(node).filter(function (part) {
  21. var encoded = part ? NodePath.getForNode(part).jsonEncode() : 'null';
  22. // Already recorded this part, filter out.
  23. if (uniqueNodesMap.hasOwnProperty(encoded)) {
  24. return false;
  25. }
  26. uniqueNodesMap[encoded] = part;
  27. return true;
  28. });
  29. // Replace with the optimized disjunction.
  30. path.replace(listToDisjunction(parts));
  31. }
  32. };