Skip to content

Commit

Permalink
fix: remove index validation (#11)
Browse files Browse the repository at this point in the history
* fix: remove index validation

* Create wet-vans-explode.md
  • Loading branch information
mew-ton authored Sep 14, 2023
1 parent 85d9a8a commit 93b598d
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 17 deletions.
5 changes: 5 additions & 0 deletions .changeset/wet-vans-explode.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"json-origami": patch
---

fix: remove index validation
19 changes: 2 additions & 17 deletions src/unfold.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,34 +37,19 @@ export function unfold<KV extends Folded<any>>(kv: KV, option?: UnfoldOption): U
...defaultCommonOption,
...option
} as FixedUnfoldOption
validateKeys(kv, fixedOpion)
validateKeys(kv)

return unfoldInternal(Object.entries(kv), fixedOpion) as Unfolded<KV>
}

const validateIndexMap = {
dot: (k) => /\.\d+/.test(k) || /^\d+/.test(k),
bracket: (k) => /\[\d+\]/.test(k)
} satisfies Record<ArrayIndex, (key: string) => boolean>

function validateKeys(kv: Folded<any>, opt: FixedUnfoldOption) {
function validateKeys(kv: Folded<any>) {
for (const key in kv) {
if (/\d+/.test(key)) {
validateNumberKey(key, opt)
}

if (key.startsWith('.') || key.endsWith('.')) {
throw new Error(`Invalid key ${key}`)
}
}
}

function validateNumberKey(key: string, { arrayIndex }: FixedUnfoldOption) {
if (!validateIndexMap[arrayIndex](key)) {
throw new Error(`Invalid key ${key}`)
}
}

const extractHeadIndexMap = {
dot: (k) => (k.match(/^(\d+)/) ?? [])[1],
bracket: (k) => (k.match(/^\[(\d+)\]/) ?? [])[1]
Expand Down

0 comments on commit 93b598d

Please sign in to comment.