You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

30 lines
920 B

2 years ago
  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: ()=>toPath
  21. });
  22. function toPath(path) {
  23. if (Array.isArray(path)) return path;
  24. let openBrackets = path.split("[").length - 1;
  25. let closedBrackets = path.split("]").length - 1;
  26. if (openBrackets !== closedBrackets) {
  27. throw new Error(`Path is invalid. Has unbalanced brackets: ${path}`);
  28. }
  29. return path.split(/\.(?![^\[]*\])|[\[\]]/g).filter(Boolean);
  30. }