Examples - tsrun
Description: tsrun code examples - TypeScript patterns and use cases.

# Examples

Code examples demonstrating tsrun features and patterns

## TypeScript Features

#### Enums & State Machine

TypeScript enums with state transitions and validation

#### Classes with Inheritance

Classes, inheritance, static blocks, private fields, getters/setters

#### Higher-Order Functions

Functions as values, composition, currying

#### Async Patterns

Async/await, Promise.all, Promise.race

#### Destructuring

Array and object destructuring, rest/spread

## Built-in Objects

#### Arrays

map, filter, reduce, find, includes, and more

#### Strings

Template literals, split, join, replace, regex

#### Map & Set

Key-value maps and unique value sets

#### RegExp

Regular expressions with match, replace, test

#### JSON

Parse and stringify with replacers/revivers

#### Date

Date creation, formatting, arithmetic

## Code Examples

### Enums & State Machine

typescript

    enum OrderState {
        Pending = "pending",
        Confirmed = "confirmed",
        Shipped = "shipped",
        Delivered = "delivered",
        Cancelled = "cancelled"
    }

    enum OrderEvent {
        Confirm = "confirm",
        Ship = "ship",
        Deliver = "deliver",
        Cancel = "cancel"
    }

    // Define valid transitions
    const transitions: Record<OrderState, Partial<Record<OrderEvent, OrderState>>> = {
        [OrderState.Pending]: {
            [OrderEvent.Confirm]: OrderState.Confirmed,
            [OrderEvent.Cancel]: OrderState.Cancelled
        },
        [OrderState.Confirmed]: {
            [OrderEvent.Ship]: OrderState.Shipped,
            [OrderEvent.Cancel]: OrderState.Cancelled
        },
        [OrderState.Shipped]: {
            [OrderEvent.Deliver]: OrderState.Delivered
        },
        [OrderState.Delivered]: {},
        [OrderState.Cancelled]: {}
    };

    class Order {
        constructor(
            public id: string,
            public state: OrderState = OrderState.Pending
        ) {}

        transition(event: OrderEvent): boolean {
            const nextState = transitions[this.state][event];
            if (nextState) {
                console.log(`Order ${this.id}: ${this.state} -> ${nextState}`);
                this.state = nextState;
                return true;
            }
            console.log(`Invalid transition: ${this.state} + ${event}`);
            return false;
        }
    }

    const order = new Order("ORD-001");
    order.transition(OrderEvent.Confirm);  // pending -> confirmed
    order.transition(OrderEvent.Ship);     // confirmed -> shipped
    order.transition(OrderEvent.Cancel);   // Invalid transition
    order.transition(OrderEvent.Deliver);  // shipped -> delivered

### Classes with Inheritance

typescript

    class Entity {
        static #count = 0;
        #id: number;

        constructor() {
            this.#id = ++Entity.#count;
        }

        get id() { return this.#id; }
        static getCount() { return Entity.#count; }
    }

    class User extends Entity {
        constructor(public name: string, public email: string) {
            super();
        }

        toJSON() {
            return { id: this.id, name: this.name, email: this.email };
        }
    }

    const user = new User("Alice", "alice@example.com");
    console.log(JSON.stringify(user.toJSON()));
    // {"id":1,"name":"Alice","email":"alice@example.com"}

### Generators

typescript

    function* fibonacci(): Generator<number> {
        let [a, b] = [0, 1];
        while (true) {
            yield a;
            [a, b] = [b, a + b];
        }
    }

    function* take<T>(gen: Generator<T>, n: number): Generator<T> {
        for (const value of gen) {
            if (n-- <= 0) return;
            yield value;
        }
    }

    const first10 = [...take(fibonacci(), 10)];
    console.log(first10);
    // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

### Async/Await

typescript

    async function fetchUserWithPosts(userId: number) {
        const [user, posts] = await Promise.all([
            fetchUser(userId),
            fetchUserPosts(userId)
        ]);
        return { user, posts };
    }

    async function processAll<T, R>(
        items: T[],
        fn: (item: T) => Promise<R>
    ): Promise<R[]> {
        const results: R[] = [];
        for (const item of items) {
            results.push(await fn(item));
        }
        return results;
    }

### Config Generation

typescript

    interface Config {
        database: { host: string; port: number; ssl?: boolean };
        logging: { level: string };
    }

    const DEFAULT_CONFIG: Config = {
        database: { host: "localhost", port: 5432 },
        logging: { level: "info" }
    };

    const envOverrides: Record<string, Partial<Config>> = {
        production: {
            database: { host: "prod-db.example.com", port: 5432, ssl: true },
            logging: { level: "warn" }
        },
        development: {
            database: { host: "localhost", port: 5432 },
            logging: { level: "debug" }
        }
    };

    function buildConfig(env: string): Config {
        const overrides = envOverrides[env] || {};
        return {
            database: { ...DEFAULT_CONFIG.database, ...overrides.database },
            logging: { ...DEFAULT_CONFIG.logging, ...overrides.logging }
        };
    }

    console.log(JSON.stringify(buildConfig("production"), null, 2));

## Embedding Examples

#### C: Basic Usage

Create values, objects, arrays, and run code

#### C: Native Functions

Register C callbacks callable from JavaScript

#### C: Module Loading

Load ES modules from virtual filesystem

#### C: Async Orders

Handle async operations via the order system

## Try it yourself

Run these examples directly in your browser with our interactive playground.

Open Playground