woocommerce/plugins/woocommerce-blocks/assets/js/data/utils/update-state.ts

38 lines
860 B
TypeScript
Raw Normal View History

2023-04-28 10:29:45 +00:00
/**
* Utility for updating nested state in the path that changed.
2023-04-28 10:29:45 +00:00
*/
function updateNested< T >( // The state being updated
state: T,
// The path being updated
path: string[],
// The value to update for the path
value: unknown,
// The current index in the path
index = 0
): T {
const key = path[ index ] as keyof T;
if ( index === path.length - 1 ) {
return { ...state, [ key ]: value };
}
const nextState = state[ key ] || {};
return {
...state,
[ key ]: updateNested( nextState, path, value, index + 1 ),
} as T;
}
2023-04-28 10:29:45 +00:00
/**
* Utility for updating state and only cloning objects in the path that changed.
*/
export default function updateState< T >(
2023-04-28 10:29:45 +00:00
// The state being updated
state: T,
2023-04-28 10:29:45 +00:00
// The path being updated
path: string[],
2023-04-28 10:29:45 +00:00
// The value to update for the path
value: unknown
): T {
return updateNested( state, path, value );
2023-04-28 10:29:45 +00:00
}