dope2/examples/enum.js

50 lines
1.9 KiB
JavaScript

import { makeCompareFn } from "../lib/compare/registry.js";
import { Int, Unit } from "../lib/primitives/primitive_types.js";
import { unit } from "../lib/primitives/unit.js";
import { makeConstructors, makeMatchFn } from "../lib/structures/enum.js";
import { enumType } from "../lib/structures/enum.types.js";
import { newProduct } from "../lib/structures/product.js";
import { lsType } from "../lib/structures/type_constructors.js";
import { prettyT } from "../lib/util/pretty.js";
const variants = [
newProduct("price")(Int),
newProduct("prices")(lsType(_ => Int)),
newProduct("not_found")(Unit),
];
const myEnumType = enumType(variants);
console.log("observe the type that was generated:");
console.log(" ", prettyT(myEnumType));
const [newPrice, newPrices, newNotFound] = makeConstructors(variants);
const price = newPrice(10);
const prices = newPrices([20, 30]);
const notFound = newNotFound(unit);
console.log("observe the encoding of different variant instances:");
console.log(" ", price);
console.log(" ", prices);
console.log(" ", notFound);
const myEnumToString = x => makeMatchFn(variants)(x)
(price => `Price: ${price}`)
(prices => `Prices: ${prices}`)
(() => "Not found!");
console.log("observe the generated match function in action:");
console.log(" ", myEnumToString(price));
console.log(" ", myEnumToString(prices));
console.log(" ", myEnumToString(notFound));
const compareMyEnum = makeCompareFn(myEnumType);
console.log("observe the generated compare function in action:");
console.log(" should be smaller ->", compareMyEnum(price)(prices));
console.log(" should be bigger ->", compareMyEnum(prices)(price));
console.log(" should be bigger ->", compareMyEnum(notFound)(price));
console.log(" should be equal ->", compareMyEnum(prices)(prices));
console.log(" should be smaller ->", compareMyEnum(newPrice(5))(newPrice(6)));
console.log(" should be bigger ->", compareMyEnum(newPrices([5, 6]))(newPrices([5, 5])));