From 246cfef21b00267bd04569715d49234de95b9af6 Mon Sep 17 00:00:00 2001 From: Tao Huang Date: Wed, 13 Mar 2024 18:37:33 +0000 Subject: [PATCH] change syntax --- readme.md | 2 +- src/operand/__test__/unit/reference.test.ts | 4 ++-- src/operand/reference.ts | 19 ++++++++++++------- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/readme.md b/readme.md index 3ada848..0dfb1f1 100644 --- a/readme.md +++ b/readme.md @@ -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: { diff --git a/src/operand/__test__/unit/reference.test.ts b/src/operand/__test__/unit/reference.test.ts index 56a6c3d..dabbd63 100644 --- a/src/operand/__test__/unit/reference.test.ts +++ b/src/operand/__test__/unit/reference.test.ts @@ -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], diff --git a/src/operand/reference.ts b/src/operand/reference.ts index 74c6324..39f5b8b 100644 --- a/src/operand/reference.ts +++ b/src/operand/reference.ts @@ -9,18 +9,23 @@ type Keys = (string | number)[] const keyWithArrayIndexRegex = /^(?[^[\]]+?)(?(?:\[\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)) { @@ -28,7 +33,7 @@ const parseKey = (key: string): Keys => { } } } else { - keys.push(key) + keys.push(unwrappedKey) } return keys })