Last active
September 19, 2019 17:59
-
-
Save golubov-andrey/c1c1ea1392b96dfc42fe08469d11bc8c 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
| import isEqual from 'lodash.isequal'; | |
| /** | |
| * Pattern matching | |
| * ``` | |
| * matching(item)( | |
| * { match: 1, then: { tag: 'Left' }} | |
| * { match: 2, then: { tag: 'Right' }} | |
| * ) | |
| * /// { tag: 'Left' } | { tag: 'Right' } | |
| * ``` | |
| * @param item any item of matching | |
| */ | |
| export function matching<T>(item: T) { | |
| return <M extends { match: T, then: any}>(...args: M[]): M['match'] extends T ? M['then'] : never => { | |
| const result = args.find(argv => (argv instanceof Array) ? argv.find(arg => isEqual(arg, item)) : isEqual(argv, item)); | |
| return result ? result.then : {}; | |
| }; | |
| } | |
| export function checkResult(response: Response) { | |
| return matching(response.status)( | |
| { match: 200, then: { tag: 'Right' as 'Right', value: response.json() } }, | |
| { match: 400, then: { tag: 'Left' as 'Left', value: new Error('Not found') }}, | |
| { match: 500, then: { tag: 'Left' as 'Left', value: new Error('Server error') }}, | |
| // TODO: { match: [501, 502, 404]: { tag: 'Left' as 'Left', value: new Error('Some problem') }}, | |
| ); | |
| } | |
| fetch('www.example.com').then(checkResult).then(v => { | |
| return v.tag === 'Right' ? Promise.resolve(v.value) : Promise.reject(v.value); | |
| }); | |
| export function checkResult2(response: Response) { | |
| return matching(response.status)( | |
| { match: 200, then: { value: response.json() } }, | |
| { match: 400, then: { value: new Error('Not found') }}, | |
| { match: 500, then: { value: new Error('Server error') }}, | |
| // TODO: { match: [501, 502, 404]: { tag: 'Left' as 'Left', value: new Error('Some problem') }}, | |
| ); | |
| } | |
| fetch('www.example.com').then(checkResult2).then(v => { | |
| return v.value instanceof Promise ? Promise.resolve(v.value) : Promise.reject(v.value); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment