Skip to content

Commit 30c10df

Browse files
committed
Update: Handle additional edge cases in set function
- Add checks to prevent invalid paths like empty strings or '[]' - Ensure correct behavior when path is just a number index
1 parent 1bbb284 commit 30c10df

2 files changed

Lines changed: 14 additions & 0 deletions

File tree

src/object.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,13 @@ export const set = <T extends object, K>(
245245
): T => {
246246
if (!initial) return {} as T
247247
if (!path || value === undefined) return initial
248+
if (
249+
typeof path !== 'string' ||
250+
!/(\w+|\[\d+\])/.test(path) ||
251+
path === '[]'
252+
) {
253+
return initial
254+
}
248255

249256
const segments: (string | number)[] =
250257
path
@@ -253,6 +260,8 @@ export const set = <T extends object, K>(
253260
segment.startsWith('[') ? Number(segment.slice(1, -1)) : segment
254261
) ?? []
255262

263+
if (segments.length === 1 && typeof segments[0] === 'number') return initial
264+
256265
const _set = (node: any) => {
257266
if (segments.length > 1) {
258267
const key = segments.shift()!

src/tests/object.test.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,11 @@ describe('object module', () => {
488488
assert.deepEqual(_.set(null as any, null as any, null as any), {})
489489
assert.deepEqual(_.set({ foo: true }, 'foo', false), { foo: false })
490490
assert.deepEqual(_.set({}, 'foo', 0), { foo: 0 })
491+
assert.deepEqual(_.set({}, '', 2), {})
492+
assert.deepEqual(_.set({}, '[]', 2), {})
493+
assert.deepEqual(_.set({}, '[0]', 2), {})
494+
assert.deepEqual(_.set({}, undefined as any, 2), {})
495+
assert.deepEqual(_.set({}, null as any, 2), {})
491496
})
492497
test('sets deep values correctly', () => {
493498
assert.deepEqual(_.set({}, 'cards.value', 2), {

0 commit comments

Comments
 (0)