Add new array method

This commit is contained in:
Sancha Pereira 2018-08-22 19:26:33 +01:00
parent cdc083665c
commit 1445408e11
3 changed files with 21 additions and 0 deletions

View File

@ -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.

View File

@ -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', () => {

View File

@ -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);