1+ import { isObject } from "@/lib/utils/isObject" ;
2+
13export type ObjPath = ( string | number ) [ ] ;
24
5+ type Obj = Record < string | number , unknown > ;
6+
37export function getValue ( obj : object , path : ObjPath ) : unknown {
48 let value : unknown = obj ;
59 for ( const key of path ) {
6- if ( typeof value === "object" ) {
7- value = ( value as unknown as Record < string , unknown > ) [ key ] ;
10+ if ( isObject ( value ) ) {
11+ value = ( value as Obj ) [ key ] ;
812 } else {
913 return undefined ;
1014 }
@@ -21,41 +25,36 @@ export function setValue<S extends object>(
2125}
2226
2327export function _setValue < S extends object > (
24- obj : S ,
28+ obj : S | undefined ,
2529 path : ObjPath ,
2630 value : unknown ,
2731) : S | undefined {
2832 if ( path . length === 1 ) {
2933 const key = path [ 0 ] ;
30- if ( typeof obj === "object" ) {
34+ if ( isObject ( obj ) ) {
3135 const oldValue = obj [ key ] ;
3236 if ( value === oldValue ) {
3337 return obj ;
3438 }
35- const newObj = Array . isArray ( obj )
36- ? ( [ ...obj ] as unknown [ ] )
37- : ( { ...obj } as Record < string , unknown > ) ;
39+ const newObj = ( Array . isArray ( obj ) ? [ ...obj ] : { ...obj } ) as Obj ;
3840 newObj [ key ] = value ;
3941 return newObj as S ;
4042 } else if ( obj === undefined ) {
41- const newObj =
42- typeof key === "number"
43- ? ( [ ] as unknown [ ] )
44- : ( { } as Record < string , unknown > ) ;
43+ const newObj = ( typeof key === "number" ? [ ] : { } ) as Obj ;
4544 newObj [ key ] = value ;
4645 return newObj as S ;
4746 }
4847 } else if ( path . length > 1 ) {
49- if ( typeof obj === "object" ) {
48+ if ( isObject ( obj ) ) {
5049 const key = path [ 0 ] ;
5150 const subObj = obj [ key ] ;
52- const newSubObj = setValue ( subObj , path . slice ( 1 ) , value ) ;
53- if ( subObj !== newSubObj ) {
54- const newObj = Array . isArray ( obj )
55- ? ( [ ...obj ] as unknown [ ] )
56- : ( { ... obj } as Record < string , unknown > ) ;
57- newObj [ key ] = newSubObj ;
58- return newObj as S ;
51+ if ( isObject ( subObj ) || subObj === undefined ) {
52+ const newSubObj = _setValue ( subObj , path . slice ( 1 ) , value ) ;
53+ if ( subObj !== newSubObj ) {
54+ const newObj = ( Array . isArray ( obj ) ? [ ...obj ] : { ... obj } ) as Obj ;
55+ newObj [ key ] = newSubObj ;
56+ return newObj as S ;
57+ }
5958 }
6059 }
6160 }
0 commit comments