Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
thecrypticace committed Dec 15, 2021
1 parent 9580b5e commit f8e155e
Showing 1 changed file with 26 additions and 25 deletions.
51 changes: 26 additions & 25 deletions src/util/toPath.js
@@ -1,3 +1,5 @@
const IS_COMPLEX_PATH = /\.{2,}|[\[\]]/g

/**
* Parse a path string into an array of path segments.
*
Expand All @@ -14,6 +16,13 @@
**/
export function toPath(path) {
if (Array.isArray(path)) return path
if (!IS_COMPLEX_PATH.test(path)) return path.split('.')

return parsePath(path)
}

function parsePath(path) {
// return parsePathFull(path)

let parts = []
let inBrackets = false
Expand Down Expand Up @@ -100,9 +109,7 @@ export function toPath(path) {
}

// Herre for reference in case one is preferred over the other
export function toPathFull(path) {
if (Array.isArray(path)) return path

function parsePathFull(path) {
// The general outline/properties of a path string:

// Tokens:
Expand Down Expand Up @@ -136,9 +143,6 @@ export function toPathFull(path) {
let error = () => {
throw new Error(`Invalid path: ${path}\n` + `${' '.repeat(14 + i)}^`)
}
let startNew = () => (partStart = i)
let advance = () => (partEnd = i)
let setInBrackets = (v) => (inBrackets = v)
let capture = () => parts.push(path.slice(partStart, partEnd))

if (prev === undefined) {
Expand All @@ -147,8 +151,8 @@ export function toPathFull(path) {
capture()
} else if (curr === '[') {
// start -> lb
startNew()
setInBrackets(true)
partStart = i
inBrackets = true
} else if (curr === ']') {
// start -> rb
return error()
Expand All @@ -161,7 +165,7 @@ export function toPathFull(path) {
return error()
} else {
// dot -> ident
startNew()
partStart = i
}
} else if (prev === '[') {
if (curr === '[' || curr === undefined) {
Expand All @@ -170,49 +174,46 @@ export function toPathFull(path) {
} else if (curr === ']') {
// lb -> rb
capture()
setInBrackets(false)
inBrackets = false
} else {
// lb -> ident
startNew()
partStart = i
}
} else if (prev === ']') {
if (curr === '.') {
// rb -> dot
startNew()
partStart = i
} else if (curr === '[') {
// rb -> lb
setInBrackets(true)
inBrackets = true
} else if (curr === undefined) {
// rb -> end
} else {
// rb -> rb | ident
return error()
}
} else {
if (curr === '[' && inBrackets) {
// ident -> lb if in brackets
return error()
}

partEnd = i

if (curr === '.' && !inBrackets) {
// ident -> dot
advance()
capture()
} else if (curr === ']') {
// ident -> rb
advance()
capture()
setInBrackets(false)
} else if (curr === '[' && inBrackets) {
// ident -> lb if in brackets
return error()
inBrackets = false
} else if (curr === '[' && !inBrackets) {
// ident -> lb
advance()
capture()
setInBrackets(true)
inBrackets = true
} else if (curr === undefined) {
// ident -> end
advance()
capture()
} else {
// ident -> ident
advance()
}
}
}
Expand Down

0 comments on commit f8e155e

Please sign in to comment.