Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created May 8, 2021 14:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save codecademydev/8322106d51384aaeafdbeef65c269aab to your computer and use it in GitHub Desktop.
Codecademy export
const initialWagonState = {
supplies: 100,
distance: 0,
days: 0,
cash: 200
};
const reducer = (state = initialWagonState, action) => {
switch(action.type){
case 'gather' : {
return {
...state,
supplies: state.supplies + 15,
days: state.days + 1,
}
}
case 'travel' : {
if(state.supplies < 0) {
return state;
}
return {
...state,
supplies: state.supplies - 20*action.payload,
distance: state.distance + 10*action.payload,
days: state.days + action.payload,
}
}
case 'tippedWagon' : {
return {
...state,
supplies: state.supplies - 30,
days: state.days + 1,
}
}
case 'sell' : {
if(state.supplies < 0) {
return state;
}
return {
...state,
supplies: state.supplies + 20,
cash: state.cash + 5
}
}
case 'buy' : {
if(state.cash < 0) {
return state;
}
return {
...state,
supplies: state.supplies + 20,
cash: state.cash - 15
}
}
case 'theft' : {
return {
...state,
cash: state.cash - state.cash*0.5
}
}
default:
return state;
}
}
let wagon = reducer(undefined, {})
console.log(wagon);
wagon = reducer(wagon, {type: 'travel', payload: 1})
console.log(wagon);
wagon = reducer(wagon, {type: 'gather'})
console.log(wagon);
wagon = reducer(wagon, {type: 'tippedWagon'})
console.log(wagon);
wagon = reducer(wagon, {type: 'travel', payload: 3})
console.log(wagon);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment