/** * External dependencies */ import { isEqual, keyBy, omit } from 'lodash'; import type { AnyAction } from '@nab/types'; /** * Internal dependencies */ import { INIT_STATE } from './config'; import type { Action } from './actions'; import type { State } from './types'; export function reducer( state = INIT_STATE, action: AnyAction ): State { return actualReducer( state, action as Action ) ?? state; } function actualReducer( state: State, action: Action ): State { switch ( action.type ) { case 'ADD_SEGMENTATION_RULE_TYPES': { const newTypes = action.segmentationRuleTypes.filter( ( type ) => ! isEqual( state.segmentationRuleTypes[ type.name ], type ) ); if ( ! newTypes.length ) { return state; } return { ...state, segmentationRuleTypes: { ...state.segmentationRuleTypes, ...keyBy( newTypes, 'name' ), }, }; } case 'REMOVE_SEGMENTATION_RULE_TYPES': { const newTypes = omit( state.segmentationRuleTypes, action.names ); if ( isEqual( state.segmentationRuleTypes, newTypes ) ) { return state; } return { ...state, segmentationRuleTypes: newTypes, }; } case 'ADD_SEGMENTATION_RULE_TYPE_CATEGORIES': { const newCategories = action.categories.filter( ( category ) => ! isEqual( state.categories[ category.name ], category ) ); if ( ! newCategories.length ) { return state; } return { ...state, categories: { ...state.categories, ...keyBy( newCategories, 'name' ), }, }; } case 'REMOVE_SEGMENTATION_RULE_TYPE_CATEGORIES': { const newCategories = omit( state.categories, action.names ); if ( isEqual( state.categories, newCategories ) ) { return state; } return { ...state, categories: newCategories, }; } } }