-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Support square bracket notation in paths
- Loading branch information
1 parent
a7263a8
commit e372011
Showing
4 changed files
with
135 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,26 @@ | ||
/** | ||
* Parse a path string into an array of path segments. | ||
* | ||
* Square bracket notation `a[b]` may be used to "escape" dots that would otherwise be interpreted as path separators. | ||
* | ||
* Example: | ||
* a -> ['a] | ||
* a.b.c -> ['a', 'b', 'c'] | ||
* a[b].c -> ['a', 'b', 'c'] | ||
* a[b.c].e.f -> ['a', 'b.c', 'e', 'f'] | ||
* a[b][c][d] -> ['a', 'b', 'c', 'd'] | ||
* | ||
* @param {string|string[]} path | ||
**/ | ||
export function toPath(path) { | ||
if (Array.isArray(path)) return path | ||
return path.split(/[\.\]\[]+/g) | ||
|
||
let openBrackets = path.split('[').length - 1 | ||
let closedBrackets = path.split(']').length - 1 | ||
|
||
if (openBrackets !== closedBrackets) { | ||
throw new Error(`Path is invalid. Has unbalanced brackets: ${path}`) | ||
} | ||
|
||
return path.split(/\.(?![^\[]*\])|[\[\]]/g).filter(Boolean) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters