Urara-Blog/node_modules/.pnpm-store/v3/files/c7/084af01f9a3309e8c84f0fdc644f82ea53bc7fb8fb15e979dfa5c3dfdfca5ef309f3b236b02feb497d4bea59088b8b2a5ead101f81b3059891290803bcaf91
2022-08-14 01:14:53 +08:00

26 lines
739 B
Text

/**
* 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
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)
}