diff --git a/readme.md b/readme.md index 7b4cdb5..265fcaa 100644 --- a/readme.md +++ b/readme.md @@ -108,6 +108,7 @@ Like all other types, you can also use a custom type to create a reducer. - resetAtIndex(value: any, index: number): Reset the value for an array element, at the specified index, with the value provided. - removeAtIndex(index: number): Remove the element from the array at the specified index. - push(value: any): Add the value to the end of the array. +- pushOrRemove(value: any): Push the value if it doesn't exist in the array or remove the element if it exists. - pop(): Remove the last element of the array. - shift(value: any): Add the value to the beginning of the array. - unshift(): Remove the first element of the array. diff --git a/src/reducers/__tests__/arrayReducer.test.js b/src/reducers/__tests__/arrayReducer.test.js index 849f8c7..3811ab4 100644 --- a/src/reducers/__tests__/arrayReducer.test.js +++ b/src/reducers/__tests__/arrayReducer.test.js @@ -71,6 +71,16 @@ describe('arrayReducer', () => { }); }); + describe('pushOrRemove', () => { + const { pushOrRemove } = DEFAULT_ARRAY_BEHAVIORS; + it('should push the payload onto the end of the array', () => { + expect(pushOrRemove.reducer([1,2,3], 4)).toEqual([1,2,3,4]); + }); + it('should remove the payload from the array', () => { + expect(pushOrRemove.reducer([1,2,3], 2)).toEqual([1,3]); + }); + }); + describe('pop', () => { const { pop } = DEFAULT_ARRAY_BEHAVIORS; it('should remove the last element from the array', () => { diff --git a/src/reducers/arrayReducer.js b/src/reducers/arrayReducer.js index d632424..0a432fe 100644 --- a/src/reducers/arrayReducer.js +++ b/src/reducers/arrayReducer.js @@ -136,6 +136,16 @@ export const DEFAULT_ARRAY_BEHAVIORS: ArrayReducerBehaviorsConfig = { }, validate: true }, + pushOrRemove: { + reducer(state, payload) { + let index = state.indexOf(payload); + if(index == -1) { + return [...state, payload]; + } + return removeAtIndex(state, index); + }, + validate: true + }, pop: { reducer(state) { return state.slice(0, -1);