Skip to content

Instantly share code, notes, and snippets.

@eduzol
Created September 5, 2017 05:08
Show Gist options
  • Save eduzol/f0f9c69512080fc17746d18b837b6be1 to your computer and use it in GitHub Desktop.
Save eduzol/f0f9c69512080fc17746d18b837b6be1 to your computer and use it in GitHub Desktop.
/* Create A Reducer
*
* You need to create a reducer called "appReducer" that accepts two arguments:
* - First, an array containing information about ice cream
* - Second, an object with a 'DELETE_FLAVOR' `type` key
* (i.e., the object contains information to delete the flavor from the state)
*
* The action your reducer will receive will look like this:
* { type: 'DELETE_FLAVOR', flavor: 'Vanilla' }
*
* And the initial state will look something like this (as such, refrain
* from passing in default values for any parameters!):
* [{ flavor: 'Chocolate', count: 36 }, { flavor: 'Vanilla', count: 210 }];
*/
const DELETE_FLAVOR = 'DELETE_FLAVOR';
var appReducer = function( state, action ){
if ( action.type === DELETE_FLAVOR ){
var newState = [];
state.forEach(function(element){
if (element.flavor!== action.flavor){
newState.push(element);
}
});
return newState;
}
return state;
};
var iceCreams = [{ flavor: 'Chocolate', count: 36 }, { flavor: 'Vanilla', count: 210 }];
var action = { type: 'DELETE_FLAVOR', flavor: 'Vanilla' };
var st = appReducer(iceCreams, action);
console.log(st);
@eduzol
Copy link
Author

eduzol commented Dec 13, 2020

function appReducer(state, action) {
if (action.type === 'DELETE_FLAVOR') {
return (state.filter(item => item.flavor !== action.flavor))
}
return state;
}

thanks bro

@mmillerPNF
Copy link

This was really helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment