Examples
cart
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.
#cart.sts
// Who changes what: a value is read-only unless it says `mut`, at the declaration and at the call.
export type Item = { name: string, cents: number, quantity: number }
export type Cart = { items: Item[], coupon?: string }
export const empty: Cart = { items: [] }
// A new cart: the one it was given is as it was.
export function add(cart: Cart, item: Item): Cart {
{ ...cart, items: [...cart.items, item] }
}
// A sorted copy.
export function cheapestFirst(items: Item[]): Item[] {
items.sortedBy(item => item.cents)
}
// The day is an argument: the same call always gives the same answer.
export function total(cart: Cart, day: number): number {
const sum = cart.items.sum(item => item.cents * item.quantity)
if (day == 5) sum * 0.9 else sum
}
export function applyCoupon(cart: Cart, coupon: string): Cart {
{ coupon, items: cart.items.map(item => ({ ...item, cents: Math.round(item.cents * 0.95) })) }
}
// Where changing in place is wanted, the signature asks for it, and so does the call: Rust's `&mut`.
export function restock(mut counts: Map<string, number>, item: Item) {
counts.set(item.name, (counts.get(item.name) ?? 0) + item.quantity)
}
export function main() {
const pen = { name: "pen", cents: 150, quantity: 2 }
const ink = { name: "ink", cents: 400, quantity: 1 }
const cart = add(add(empty, pen), ink)
console.log(`${cheapestFirst(cart.items).map(item => item.name).join(", ")}: ${total(cart, 1)} cents, ${total(cart, 5)} on a Friday`)
console.log(`with a coupon: ${total(applyCoupon(cart, "SPRING"), 1)} cents`)
const mut stock: Map<string, number> = Map.from([{ key: "pen", value: 10 }])
for (const item of cart.items) {
restock(mut stock, item)
}
// Given away as a value nobody can change: from here on `stock` is no longer a name to use.
const counted: Map<string, number> = stock
for (const entry of counted.entries()) {
console.log(`${entry.key}: ${entry.value}`)
}
}