Created
February 5, 2021 00:17
-
-
Save maciejsmolinski/1729858438948ef7795986b0da6673dd to your computer and use it in GitHub Desktop.
Union types, pattern matching and exhaustiveness in today's JavaScript https://notes.maciejsmolinski.com/2021/02/03/union-types-pattern-matching-and-exhaustiveness-in-todays-javascript/
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
const daggy = require('daggy'); | |
const Status = daggy.taggedSum('Status', { | |
Pending: [], | |
Done: [], | |
Failed: ['reason'], | |
}); | |
const jobs = [ | |
{ id: 1, status: Status.Pending }, | |
{ id: 2, status: Status.Done }, | |
{ id: 3, status: Status.Completed }, // <- notice the wrong status | |
]; | |
function normalize(job) { | |
if (!Status.is(job.status)) { | |
return { | |
...job, | |
status: Status.Failed('Invalid job status') | |
}; | |
} | |
return job; | |
} | |
function execute(job) { | |
return job.status.cata({ | |
Pending: () => { | |
console.log(`Executing job#${job.id}..`); | |
return { ...job, status: Status.Done }; | |
}, | |
Done: () => job, | |
Failed: (reason) => { | |
console.log(`Job#${job.id} failed with "${reason}".`); | |
return job; | |
}, | |
}); | |
} | |
jobs.map(normalize).forEach(execute); | |
// Executing job#1.. | |
// Job#3 failed with "Invalid job status" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment