Skip to content

Commit

Permalink
change syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
countcain committed Mar 13, 2024
1 parent 5a835b6 commit 246cfef
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ If the key of the nested reference includes the "." delimiter, please wrap the w
}
```

`` $address.`city.code[0]` `` can reference the object
`` $address.`city.code`[0] `` can reference the object
```javascript
{
address: {
Expand Down
4 changes: 2 additions & 2 deletions src/operand/__test__/unit/reference.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ describe('Operand - Value', () => {
['RefC.subA', 2],
['RefC.subB.subSubA', 3],
['RefC.`subC.dotKey`.subSubC', 4],
['RefC.`subD.dotKey[0]`.subSubD', 5],
['RefC.`subD.dotKey[0]`.subSubE[0].subSubSubE', 6],
['RefC.`subD.dotKey`[0].subSubD', 5],
['RefC.`subD.dotKey`[0].subSubE[0].subSubSubE', 6],
// Missing
['RefB', undefined],
['RefC.subC', undefined],
Expand Down
19 changes: 12 additions & 7 deletions src/operand/reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,31 @@ type Keys = (string | number)[]
const keyWithArrayIndexRegex =
/^(?<currentKey>[^[\]]+?)(?<indexes>(?:\[\d+])+)?$/
const arrayIndexRegex = /\[(\d+)]/g

const parseBacktickWrappedKey = (key: string) =>
key.startsWith('`') && key.endsWith('`') ? key.slice(1, -1) : key

const parseKey = (key: string): Keys => {
const keys = key.match(/(`.+`|[^`.]+)/g)
const keys = key.match(/(`.+`(\[\d+\])*|[^`.]+)/g)
return !keys
? []
: keys.flatMap((key) => {
if (key.startsWith('`') && key.endsWith('`')) {
key = key.slice(1, -1)
}
const parseResult = keyWithArrayIndexRegex.exec(key)
const unwrappedKey = parseBacktickWrappedKey(key)
const keys: Keys = []
const parseResult = keyWithArrayIndexRegex.exec(unwrappedKey)
if (parseResult) {
keys.push(parseResult?.groups?.currentKey ?? key)
const extractedKey = parseBacktickWrappedKey(
parseResult?.groups?.currentKey ?? unwrappedKey
)
keys.push(extractedKey)
const rawIndexes = parseResult?.groups?.indexes
if (rawIndexes) {
for (const indexResult of rawIndexes.matchAll(arrayIndexRegex)) {
keys.push(parseInt(indexResult[1]))
}
}
} else {
keys.push(key)
keys.push(unwrappedKey)
}
return keys
})
Expand Down

0 comments on commit 246cfef

Please sign in to comment.