11import { isObject } from "@/lib/utils/isObject" ;
22
33export type ObjPath = ( string | number ) [ ] ;
4+ export type ObjPathLike = ObjPath | string | number | undefined | null ;
45
56type Obj = Record < string | number , unknown > ;
67
7- export function getValue (
8- obj : object | undefined ,
9- path : ObjPath | string ,
10- ) : unknown {
8+ export function getValue ( obj : object | undefined , path : ObjPathLike ) : unknown {
119 path = toObjPath ( path ) ;
1210 let value : unknown = obj ;
1311 for ( const key of path ) {
@@ -22,7 +20,7 @@ export function getValue(
2220
2321export function setValue < S extends object | undefined > (
2422 obj : S ,
25- path : ObjPath | string ,
23+ path : ObjPathLike ,
2624 value : unknown ,
2725) : S {
2826 return _setValue ( obj , toObjPath ( path ) , value ) ;
@@ -65,17 +63,15 @@ export function _setValue<S extends object | undefined>(
6563 return obj ;
6664}
6765
68- export function toObjPath (
69- property : ObjPath | string | number | undefined | null ,
70- ) : ObjPath {
71- if ( Array . isArray ( property ) ) {
72- return property as ObjPath ;
73- } else if ( ! property || property === "" ) {
66+ export function toObjPath ( pathLike : ObjPathLike ) : ObjPath {
67+ if ( Array . isArray ( pathLike ) ) {
68+ return pathLike as ObjPath ;
69+ } else if ( ! pathLike || pathLike === "" ) {
7470 return [ ] ;
75- } else if ( typeof property === "number" ) {
76- return [ property ] ;
71+ } else if ( typeof pathLike === "number" ) {
72+ return [ pathLike ] ;
7773 } else {
78- const objPath : ObjPath = property . split ( "." ) ;
74+ const objPath : ObjPath = pathLike . split ( "." ) ;
7975 for ( let i = 0 ; i < objPath . length ; i ++ ) {
8076 const index = Number ( objPath [ i ] ) ;
8177 if ( Number . isInteger ( index ) ) {
@@ -85,3 +81,15 @@ export function toObjPath(
8581 return objPath ;
8682 }
8783}
84+
85+ export function equalObjPaths ( pathLike1 : ObjPathLike , pathLike2 : ObjPathLike ) {
86+ if ( pathLike1 === pathLike2 ) {
87+ return true ;
88+ }
89+ const path1 = toObjPath ( pathLike1 ) ;
90+ const path2 = toObjPath ( pathLike2 ) ;
91+ return (
92+ path1 . length === path2 . length &&
93+ path1 . every ( ( item , index ) => item === path2 [ index ] )
94+ ) ;
95+ }
0 commit comments