Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created May 13, 2022 20:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codecademydev/a82decabc24a094b525d0a7e69a48d33 to your computer and use it in GitHub Desktop.
Save codecademydev/a82decabc24a094b525d0a7e69a48d33 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 - (action.payload * 20) >= 0) {
return {
...state,
supplies: state.supplies - (action.payload * 20),
distance: state.distance + (action.payload * 10),
days: state.days + action.payload
}
} else {
return state;
}
case 'tippedWagon':
if (state.cash >= 30) {
return {
...state,
supplies: state.supplies - 30,
days: state.days + 1
}
} else {
return {
...state,
supplies: 0,
days: state.days + 1
}
}
//Additions
case 'sell':
if (state.supplies >= 20) {
return {
...state,
supplies: state.supplies - 20,
cash: state.cash + 5
}
} else {
return state;
}
case 'buy':
if (state.cash >= 15) {
return {
...state,
supplies: state.supplies + 25,
cash: state.cash - 15
}
} else {
return state;
}
case 'theft':
return {
...state,
cash: state.cash / 2
}
default:
return state;
}
}
let wagon = reducer(undefined, {});
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: 'travel', payload: 3 })
console.log(wagon);
//Extra Credit
wagon = reducer(wagon, { type: 'sell' })
console.log(wagon); //Shouldn't do anything
wagon = reducer(wagon, { type: 'buy' })
console.log(wagon);
wagon = reducer(wagon, { type: 'theft' })
console.log(wagon);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment