Enum-FP
Functional Enum type / Sum type for javascript with simple pattern matching
Checkout the docs for more information
Medium article on SumTypes using EnumFP
Install
To add the project to your project
yarn add enum-fp
Usage
Import it to your file
;
Create an enum type
const Action = ; // Or with a fixed number of argumentsconst Maybe = ;
Create an instance of the type using one of the contructors
const action = Action;
Pattern matching
const Action = ; const logMessage = console; ; // >> Adding "Earth"; // >> Adding "Earth 2"; // >> Adding "Pluto"; // >> Editing [2] to "Mars"; // >> Deleting [3]; // >> Adding "Pluto"; // >> Deleting all entries // As Get action is not handled in the pattern, it will execute the default; // >> Unknown action
Type validation
You can add strict type validation instead of argument descriptions. You can read more about types module here
; const TodoAction = ;
NOTE: The string passed to the functions are just for documentation purposes and are optional. It won't affect the behavior of the type in any way.
Enum use cases
In the react world
You can use it to manage react component state! Checkout the documentation
Safely work with empty/invalid states
- Working with invalid values
// Just an example. You should use `Maybe` functor in cases like theseconst Value = ; const getName = user && username ? Value : Value; const splitBySpace = Value; const firstName lastName = ;
In the functional world
- Maybe
const Maybe = ; const fmap = Maybe;
- Either
const Either = ; const fmap = Either;const fmapFail = Either;