-
-
Save codecademydev/1cf8a159d792aad426fb3b5da9396d1c to your computer and use it in GitHub Desktop.
Codecademy export
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 - (20 * action.payload) <= 0) { | |
return state; | |
} else { | |
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': | |
return { | |
...state, | |
supplies: state.supplies - 20, | |
cash: state.cash + 5 | |
} | |
case 'buy': | |
return { | |
...state, | |
supplies: state.supplies + 25, | |
cash: state.cash - 15 | |
} | |
case 'theft': | |
return { | |
...state, | |
cash: state.cash / 2 | |
} | |
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); | |
wagon = reducer(wagon, {type: 'sell', payload: 3}); | |
console.log(wagon); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment