Skip to content

Commit 753502c

Browse files
committed
refactor: improve readability of setDotProp function
closes #101
1 parent 1c3c224 commit 753502c

1 file changed

Lines changed: 19 additions & 15 deletions

File tree

src/utils.ts

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -102,24 +102,28 @@ export const camelcase = (input: string): string => {
102102
}
103103

104104
export function setDotProp(
105-
obj: { [k: string]: any },
105+
obj: Record<string, any>,
106106
keys: string[],
107107
val: any,
108108
): void {
109-
let i = 0
110-
const length = keys.length
111-
let t = obj
112-
let x
113-
for (; i < length; ++i) {
114-
x = t[keys[i]]
115-
t = t[keys[i]] =
116-
i === length - 1
117-
? val
118-
: x == null
119-
? !!~keys[i + 1].indexOf('.') || !(+keys[i + 1] > -1)
120-
? {}
121-
: []
122-
: x
109+
let current = obj
110+
111+
for (let i = 0; i < keys.length; i++) {
112+
const key = keys[i]
113+
const isLastKey = i === keys.length - 1
114+
115+
if (isLastKey) {
116+
current[key] = val
117+
return
118+
}
119+
120+
if (current[key] == null) {
121+
const nextKey = keys[i + 1]
122+
const nextKeyIsArrayIndex = +nextKey > -1
123+
current[key] = nextKeyIsArrayIndex ? [] : {}
124+
}
125+
126+
current = current[key]
123127
}
124128
}
125129

0 commit comments

Comments
 (0)