tutorials/frontendJS/full-stack-react-redux/voting-client/src/reducer.js

42 lines
809 B
JavaScript

import {Map} from 'immutable';
const SET_STATE = 'SET_STATE';
const VOTE = 'VOTE';
function setState(state, newState) {
return state.merge(newState);
}
function vote(state, entry) {
const currentPair = state.getIn(['vote', 'pair']);
if (currentPair && currentPair.includes(entry)) {
return state.set('hasVoted', entry);
}
return state;
}
function resetVote(state) {
const hasVoted = state.get('hasVoted');
const currentPair = state.getIn(['vote', 'pair']);
if (hasVoted && ! currentPair.includes(hasVoted)) {
return state.remove('hasVoted');
}
return state;
}
export default function(state = Map(), action) {
switch(action.type) {
case SET_STATE:
return resetVote(setState(state, action.state));
case VOTE:
return vote(state, action.entry);
default:
return state;
}
}