toPath.js 951 B

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. * Parse a path string into an array of path segments.
  3. *
  4. * Square bracket notation `a[b]` may be used to "escape" dots that would otherwise be interpreted as path separators.
  5. *
  6. * Example:
  7. * a -> ['a']
  8. * a.b.c -> ['a', 'b', 'c']
  9. * a[b].c -> ['a', 'b', 'c']
  10. * a[b.c].e.f -> ['a', 'b.c', 'e', 'f']
  11. * a[b][c][d] -> ['a', 'b', 'c', 'd']
  12. *
  13. * @param {string|string[]} path
  14. **/ "use strict";
  15. Object.defineProperty(exports, "__esModule", {
  16. value: true
  17. });
  18. Object.defineProperty(exports, "toPath", {
  19. enumerable: true,
  20. get: function() {
  21. return toPath;
  22. }
  23. });
  24. function toPath(path) {
  25. if (Array.isArray(path)) return path;
  26. let openBrackets = path.split("[").length - 1;
  27. let closedBrackets = path.split("]").length - 1;
  28. if (openBrackets !== closedBrackets) {
  29. throw new Error(`Path is invalid. Has unbalanced brackets: ${path}`);
  30. }
  31. return path.split(/\.(?![^\[]*\])|[\[\]]/g).filter(Boolean);
  32. }