Examples
report
The sources of the example, as they are at the commit this site was built from. Examples says what each example is about, and the playground runs a text of the language in the page.
#report.sts
// What throws without saying so in JavaScript: here each failure is in a type, and nothing else can throw.
export type Sale = { product: string, cents: number, tags: string[] }
extern {
type RegExp
function RegExp.new(source: string, flags: string): RegExp
function RegExp.test(text: string): boolean
}
export function readSales(json: string): Result<Sale[], string> {
const value = JSON.parse(json).mapErr(error => error.message)?
SaleList.parse(value).mapErr(error => `at ${error.path}: expected ${error.expected}`)
}
type SaleList = Sale[]
export function matching(sales: Sale[], source: string): Result<Sale[], string> {
const wanted = RegExp.new(source, "i").mapErr(thrown => thrown.message)?
// A regular expression that was made does not throw when it is asked: a call to the outside says it may all the same.
Ok(sales.filter(sale => wanted.test(sale.product).unwrapOr(false)))
}
// `BigInt(1.5)` throws, and so does a division by zero: both are in the type.
export function average(sales: Sale[]): Result<bigint, string> {
const total = BigInt(sales.sum(sale => sale.cents)).okOr("a price is not a whole number of cents")?
const count = BigInt(sales.length).okOr("not a count")?
(total / count).okOr("no sale matches")
}
export function euros(cents: number): string {
(cents / 100).toFixed(2) ?? "?"
}
export function line(sale: Sale): string {
`${sale.product}: ${euros(sale.cents)} [${sale.tags.join(", ")}]`
}
export function report(json: string, source: string): Result<string, string> {
const sales = matching(readSales(json)?, source)?
const mean = average(sales)?
Ok([...sales.map(line), `average: ${euros(Number(mean))}`].join("\n"))
}
export function main(args: string[]): Result<void, string> {
const json = args[0] ?? `[{"product":"Pen","cents":150,"tags":["office"]},{"product":"Pencil","cents":80,"tags":[]},{"product":"Ink","cents":400,"tags":["office","refill"]}]`
console.log(report(json, args[1] ?? "pen")?)
Ok()
}