File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11'use strict'
22
33module . exports = function set ( object , path , value ) {
4- const pathArr = path . split ( '.' )
5- let property = object
6- let i
7- for ( i = 0 ; i < pathArr . length - 1 ; i ++ ) {
8- const n = pathArr [ i ]
9- if ( property . hasOwnProperty ( n ) ) {
10- property = property [ n ]
11- } else {
12- property [ n ] = property = { }
4+ let index = - 1
5+ while ( true ) {
6+ const nextIndex = path . indexOf ( '.' , index + 1 )
7+ if ( nextIndex === - 1 ) {
8+ object [ path . slice ( index + 1 ) ] = value
9+ return
1310 }
11+ object = object [ path . slice ( index + 1 , nextIndex ) ] ??= { }
12+ index = nextIndex
1413 }
15- property [ pathArr [ i ] ] = value
1614}
Original file line number Diff line number Diff line change @@ -9,7 +9,9 @@ describe('set', () => {
99 const obj = { }
1010
1111 it ( 'should set value at path' , ( ) => {
12- set ( obj , 'a.b' , 'c' )
13- expect ( obj . a . b ) . to . be . equal ( 'c' )
12+ set ( obj , 'a' , 1 )
13+ set ( obj , 'b.c' , 2 )
14+ set ( obj , 'b.d.e' , 3 )
15+ expect ( obj ) . to . deep . equal ( { a : 1 , b : { c : 2 , d : { e : 3 } } } )
1416 } )
1517} )
You can’t perform that action at this time.
0 commit comments