Skip to content

Commit

Permalink
Add graceful support and more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
tyxla committed Mar 13, 2023
1 parent f69c57d commit 37cf182
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/core-data/src/utils/set-nested-value.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
* @param {*} value Value to set.
*/
export default function setNestedValue( object, path, value ) {
if ( ! object || typeof object !== 'object' ) {
return object;
}

path.reduce( ( acc, key, idx ) => {
if ( acc[ key ] === undefined ) {
if ( Number.isInteger( path[ idx + 1 ] ) ) {
Expand Down
21 changes: 21 additions & 0 deletions packages/core-data/src/utils/test/set-nested-value.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ describe( 'setNestedValue', () => {
expect( result ).toEqual( { x: [ { z: 123 } ] } );
} );

it( 'should also work with arrays', () => {
const result = setNestedValue( [], [ 0, 1, 2 ], 123 );

expect( result ).toEqual( [ [ , [ , , 123 ] ] ] );
} );

it( 'should keep remaining properties unaffected', () => {
const input = { x: { y: { z: 123, z1: 'z1' }, y1: 'y1' }, x1: 'x1' };
const result = setNestedValue( input, [ 'x', 'y', 'z' ], 456 );
Expand All @@ -48,4 +54,19 @@ describe( 'setNestedValue', () => {
expect( result ).toBe( input );
expect( result ).toEqual( { x: 'z' } );
} );

it.each( [
undefined,
null,
0,
5,
NaN,
Infinity,
'test',
false,
true,
Symbol( 'foo' ),
] )( 'should return the original input if it is %s', ( value ) => {
expect( setNestedValue( value, [ 'x' ], 123 ) ).toBe( value );
} );
} );

0 comments on commit 37cf182

Please sign in to comment.