Skip to content

Instantly share code, notes, and snippets.

@tatchi
Created February 2, 2019 12:45
Show Gist options
  • Select an option

  • Save tatchi/fa520d252dcbe0a0932a2c7d693d4a3c to your computer and use it in GitHub Desktop.

Select an option

Save tatchi/fa520d252dcbe0a0932a2c7d693d4a3c to your computer and use it in GitHub Desktop.
export const createSumType = types => {
const values = Object.values(types);
return Object.entries(types).reduce(
(acc, [k, v]) => ({
...acc,
[k]: {
value: v,
matchWith: o => {
const keys = Object.keys(o);
if (!keys.includes("_")) {
if (
keys.filter(k => k !== "_").length !== values.length ||
!Object.values(types).every(v => keys.includes(v))
) {
throw new Error("Not all pattern");
}
}
return o[v] ? o[v]() : o._ ? o._() : null;
}
}
}),
{}
);
};
const ChoiceTypes = {
None: "none",
Agence: "agence",
Mobile: "mobile"
};
const Choices = createSumType(ChoiceTypes);
renderDetail = () => {
return this.state.selectedChoice.matchWith({
[ChoiceTypes.Mobile]: () => <MobileDetails />,
[ChoiceTypes.Agence]: () => <AgencyDetails />,
[ChoiceTypes.None]: () => null
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment