diff --git a/package.json b/package.json index bdb1324..4fa68ae 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,8 @@ "lodash.keys": "^4.2.0", "lodash.map": "^4.6.0", "lodash.omit": "^4.5.0", + "lodash.findindex": "^4.6.0", + "lodash.isequal": "^4.5.0", "redux": "4.0.0" } } diff --git a/src/reducers/__tests__/arrayReducer.test.js b/src/reducers/__tests__/arrayReducer.test.js index 3811ab4..c906061 100644 --- a/src/reducers/__tests__/arrayReducer.test.js +++ b/src/reducers/__tests__/arrayReducer.test.js @@ -73,12 +73,36 @@ describe('arrayReducer', () => { describe('pushOrRemove', () => { const { pushOrRemove } = DEFAULT_ARRAY_BEHAVIORS; - it('should push the payload onto the end of the array', () => { + it('should push the primitive 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', () => { + it('should remove the primitive payload from the array', () => { expect(pushOrRemove.reducer([1,2,3], 2)).toEqual([1,3]); }); + it('should push the object payload onto the end of the array', () => { + let users = [ + { 'user': 'barney', 'active': false }, + { 'user': 'fred', 'active': false } + ]; + let expected_users = [ + { 'user': 'barney', 'active': false }, + { 'user': 'fred', 'active': false }, + { 'user': 'pebbles', 'active': true } + ]; + expect(pushOrRemove.reducer(users, { 'user': 'pebbles', 'active': true })).toEqual(expected_users); + }); + it('should remove the object payload from the array', () => { + let users = [ + { 'user': 'barney', 'active': false }, + { 'user': 'fred', 'active': false }, + { 'user': 'pebbles', 'active': true } + ]; + let expected_users = [ + { 'user': 'barney', 'active': false }, + { 'user': 'pebbles', 'active': true } + ]; + expect(pushOrRemove.reducer(users, { 'user': 'fred', 'active': false })).toEqual(expected_users); + }); }); describe('pop', () => { diff --git a/src/reducers/arrayReducer.js b/src/reducers/arrayReducer.js index 0a432fe..2f7f130 100644 --- a/src/reducers/arrayReducer.js +++ b/src/reducers/arrayReducer.js @@ -59,6 +59,7 @@ import { createReducerBehaviors } from "../reducers"; import { updateAtIndex, removeAtIndex } from "../utils/arrayUtils"; import { PROP_TYPES } from "../structure"; import { isCombinedAction, getApplicableCombinedActions } from "./batchUpdates"; +import { findIndex, isEqual } from "lodash/fp"; const reduce = require("lodash/fp/reduce").convert({ cap: false }); @@ -138,7 +139,7 @@ export const DEFAULT_ARRAY_BEHAVIORS: ArrayReducerBehaviorsConfig = { }, pushOrRemove: { reducer(state, payload) { - let index = state.indexOf(payload); + let index = findIndex(isEqual(payload))(state); if(index == -1) { return [...state, payload]; }