https://github.com/futantan/swifty-enum
JavaScript Enum in Swift way
https://github.com/futantan/swifty-enum
associated-values enum javascript
Last synced: 3 months ago
JSON representation
JavaScript Enum in Swift way
- Host: GitHub
- URL: https://github.com/futantan/swifty-enum
- Owner: futantan
- License: mit
- Created: 2018-08-29T01:09:34.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T11:20:41.000Z (almost 3 years ago)
- Last Synced: 2024-11-16T15:39:00.473Z (11 months ago)
- Topics: associated-values, enum, javascript
- Language: JavaScript
- Homepage:
- Size: 328 KB
- Stars: 4
- Watchers: 3
- Forks: 0
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Swifty-Enum
[](https://circleci.com/gh/futantan/swifty-enum)
[](https://github.com/futantan/swifty-enum/blob/master/LICENSE)
[](https://www.npmjs.com/package/swifty-enum)
[]()
[](https://codecov.io/gh/futantan/swifty-enum)
This repo helps you use Enum in [Swift way](https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html).## Install
Install using npm:```bash
npm install --save swifty-enum
```## Create An Enum Type
```js
const Direction = Enum(['North', 'South', 'East', 'West']);
```Now, you get a new type: `Direction`, which contains four cases:
* North
* South
* East
* WestYou can directly use a case by `Direction.North`, or invoke it with `Direction.North()`. You can pass associated values in(optionally).
Use `Enum.type()` to get the type of the case.
Use `Direction.types` to get all cases types.```js
// Direction is an Enum type.
const myDirection = Direction.North;
switch (Enum.type(myDirection)) {
case Direction.types.North:
console.log('North');
break;
case Direction.types.South:
console.log('South');
break;
case Direction.types.East:
console.log('East');
break;
case Direction.types.West:
console.log('West');
break;
default:
break;
}
// it will log out 'North'
```## Use with associated values
Use `addCase` to add a plain case, or `addCaseWithAssociatedValues` to add a case with values.
```js
const AsyncState = Enum()
.addCase('Loading')
.addCaseWithAssociatedValues('Succeed', ['payload'])
.addCaseWithAssociatedValues('Failed', ['error'])
.build();
```Now you get a `AsyncState`, it will give you 3 function
* Loading
* Succeed
* FailedYou can call the function with associated values you want to put in.
```js
const { Loading, Succeed, Failed } = AsyncState;
let state = Loading();
axios.get('https://httpbin.org/get?name=alice')
.then((resp) => {
state = Succeed({ payload: resp })
console.log(state);
})
.catch(error => {
state = Failed({ error: error })
console.log(state);
})
```If the request succeed, you can put the resp in `Succeed` case, and get that value via `Enum.values(state).payload`.
If the request failed, you use a `Failed` to represent that case, and retrieve the error using `Enum.values(state).error`.