Created
February 2, 2019 12:45
-
-
Save tatchi/fa520d252dcbe0a0932a2c7d693d4a3c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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