├── package.json ├── index.js ├── LICENSE └── README.md /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tagged-union", 3 | "version": "1.1.0", 4 | "description": "Tagged unions in vanilla JavaScript!", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/quadrupleslap/union-js.git" 12 | }, 13 | "keywords": [ 14 | "tagged", 15 | "union", 16 | "discriminated", 17 | "variant", 18 | "sum" 19 | ], 20 | "author": "Ram Kaniyur", 21 | "license": "MIT", 22 | "bugs": { 23 | "url": "https://github.com/quadrupleslap/union-js/issues" 24 | }, 25 | "homepage": "https://github.com/quadrupleslap/union-js#readme" 26 | } 27 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var Union = (function () { 2 | 3 | function Union(kinds) { 4 | var self = this; 5 | kinds.forEach(function (kind) { 6 | self[kind] = function () { 7 | return new Instance(kind, Array.from(arguments)); 8 | }; 9 | }); 10 | } 11 | 12 | function Instance(kind, data) { 13 | this.kind = kind; 14 | this.data = data; 15 | } 16 | 17 | Union.fromJSON = function (jsonObject) { 18 | return new Instance(jsonObject.kind, jsonObject.data); 19 | }; 20 | 21 | Instance.prototype.match = function (clauses) { 22 | if (this.kind in clauses) { 23 | return clauses[this.kind].apply(undefined, this.data); 24 | } else if (clauses.hasOwnProperty('_')) { 25 | return clauses._(); 26 | } else { 27 | throw new Error('Case not matched: ' + this.kind); 28 | } 29 | }; 30 | 31 | Instance.prototype.toString = function () { 32 | return this.kind + '(' + this.data.join(', ') + ')'; 33 | }; 34 | 35 | return Union; 36 | 37 | })(); 38 | 39 | if (typeof module !== 'undefined') { 40 | module.exports = Union; 41 | } else { 42 | window.Union = Union; 43 | } 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Ram Kaniyur 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tagged-union 2 | 3 | Tagged unions, **in vanilla JavaScript**. 4 | 5 | ```sh 6 | npm install tagged-union 7 | ``` 8 | 9 | ## What's a tagged union? 10 | 11 | Tagged unions are the idea that a thing can be one of many things, but you want to keep track of which of those things the thing is. They're simple and *really* useful. 12 | 13 | ## I definitely understood all of that. So, how does it work? 14 | 15 | Well, let's go through an example with some variables that can hold either `Good` or `Bad` people, where: 16 | 17 | - Good people have chocolate. 18 | - Bad people have toast with a vegetable (one vegetable! :frowning:) 19 | 20 | ```javascript 21 | const Union = require('tagged-union'); 22 | 23 | // Define the things that a person can be. 24 | 25 | const Person = new Union(['Good', 'Bad']); 26 | 27 | // Make some people! 28 | 29 | let alice = Person.Bad('burnt', 'broccoli'); 30 | let bob = Person.Good('lindt'); 31 | 32 | console.log(alice.toString()); // => Bad(burnt, broccoli) 33 | 34 | // Good people go to heaven, bad people go to hell. 35 | 36 | function afterlife(person) { 37 | // Note that match clauses can, but don't have to, return a value. 38 | 39 | return person.match({ 40 | Good(chocolate) { 41 | return 'heaven'; 42 | }, 43 | Bad(toast, vegetable) { 44 | return 'hell'; 45 | }, 46 | _() { 47 | // A function named '_' catches every kind without its own clause, 48 | // which in this case is none of them. 49 | throw new Error('We can\'t get here!'); 50 | } 51 | }); 52 | } 53 | 54 | console.log(afterlife(alice)); // => hell 55 | console.log(afterlife(bob)); // => heaven 56 | 57 | // Oh, and did I mention that they can be serialized? 58 | 59 | let bobInABox = JSON.stringify(bob); 60 | let bobClone = Union.fromJSON(JSON.parse(bobInABox)); 61 | 62 | console.log(bobClone.toString()); // => Good(lindt) 63 | ``` 64 | 65 | ## That's cool and all, but why's it useful again? 66 | 67 | Your SPA only has a couple of screens, a result can either be successful or an error, trees are made of nodes and leaves, and there are only half a dozen ways you can pay for something online. The (programming) world is full of discriminated unions! Without the proper abstraction, you end up with manually tagged unions, which are the worst kind, because you have to manually track what's actually in the object. Here, you can just `match` on it, and it's all rainbows and sunshine. 68 | 69 | :rainbow: and :sunny:. 70 | --------------------------------------------------------------------------------