Skip to content

Instantly share code, notes, and snippets.

@ajcrites
Last active March 18, 2019 22:22
Show Gist options
  • Save ajcrites/a84c84ecd670266f2ccb6c680dcc2404 to your computer and use it in GitHub Desktop.
Save ajcrites/a84c84ecd670266f2ccb6c680dcc2404 to your computer and use it in GitHub Desktop.
import parse from 'parse-color';
export function colorReducer(state = {}, action): ColorContextProps {
switch (action.type) {
case 'UPDATE_HEX': {
let nextState = { ...state };
const hexColor = action.payload;
if (/^#[a-f0-9]{6}$/i.test(hexColor)) {
const { hex, rgba } = parse(action.payload);
nextState = {
...state,
hex,
rgba,
}
}
return nextState;
}
case 'UPDATE_RGBA': {
let nextState = { ...state };
const rgbaColor = action.payload;
if (!rgbaColor.some(isNaN)) {
const { hex, rgba } = parse(action.payload);
nextState = {
...state,
hex,
rgba,
}
}
return nextState;
}
default:
return state;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment