Skip to content

Bint Examples

Real-world examples and common patterns for using Bint in your applications.

WebSocket Data Transmission

Efficiently transmit data over WebSocket:

ts
import bint from "@briklab/net-t";

class NetworkClient {
  private websocket: WebSocket;

  constructor(url: string) {
    this.websocket = new WebSocket(url);
    this.setupListeners();
  }

  private setupListeners(): void {
    this.websocket.onmessage = (event: MessageEvent) => {
      const buffer = event.data as ArrayBuffer;
      const data = bint.fromBuffer(buffer);

      console.log("Received values:");
      for (const value of data.values()) {
        console.log(value);
      }
    };
  }

  sendMetrics(metrics: number[]): void {
    const instance = bint();
    metrics.forEach(m => instance(m));

    // Send binary data (much smaller than JSON)
    this.websocket.send(instance.toBuffer());
  }
}

const client = new NetworkClient("ws://localhost:8080");
client.sendMetrics([150, 145, 148, 152, 149]);

IndexedDB Storage

Store numerical arrays efficiently in browser storage:

ts
import bint from "@briklab/net-t";

class LocalStorage {
  private db: IDBDatabase;

  async store(key: string, data: number[]): Promise<void> {
    // Compress to binary
    const instance = bint();
    data.forEach(num => instance(num));
    const buffer = instance.toBuffer();

    // Store in IndexedDB
    const transaction = this.db.transaction(["data"], "readwrite");
    const store = transaction.objectStore("data");
    await store.put({ key, buffer, size: buffer.byteLength });
  }

  async retrieve(key: string): Promise<number[]> {
    const transaction = this.db.transaction(["data"], "readonly");
    const store = transaction.objectStore("data");
    const result = await store.get(key);

    if (result && result.buffer) {
      const instance = bint.fromBuffer(result.buffer);
      return Array.from(instance.values());
    }

    return [];
  }
}

// Store 1000 numbers
const storage = new LocalStorage();
await storage.store("metrics", Array.from({ length: 1000 }, () => Math.random() * 100));

Live Demo - Real-world Usage

Console
No logs yet.

Statistics Calculator

Calculate statistics on efficiently-stored data:

ts
import bint from "@briklab/net-t";

class Statistics {
  calculate(buffer: ArrayBuffer): {
    mean: number;
    min: number;
    max: number;
    count: number;
  } {
    const instance = bint.fromBuffer(buffer);
    let sum = 0;
    let min = Infinity;
    let max = -Infinity;
    let count = 0;

    for (const value of instance) {
      const num = typeof value === "bigint" ? Number(value) : value;
      sum += num;
      min = Math.min(min, num);
      max = Math.max(max, num);
      count++;
    }

    return {
      mean: sum / count,
      min,
      max,
      count
    };
  }
}

const stats = new Statistics();
const calculator = bint();
[10, 20, 30, 40, 50].forEach(n => calculator(n));

const result = stats.calculate(calculator.toBuffer());
console.log("Mean:", result.mean);     // 30
console.log("Min:", result.min);       // 10
console.log("Max:", result.max);       // 50

Sensor Data Logging

Log IoT sensor data efficiently:

ts
import bint from "@briklab/net-t";

class SensorLogger {
  private readings = bint();

  logTemperature(celsius: number): void {
    this.readings(celsius);
  }

  logHumidity(percent: number): void {
    this.readings(percent);
  }

  logPressure(hpa: number): void {
    this.readings(hpa);
  }

  export(): ArrayBuffer {
    return this.readings.toBuffer();
  }

  getSize(): { bytes: number; readings: number } {
    return {
      bytes: this.readings.toBuffer().byteLength,
      readings: this.readings.length
    };
  }
}

const logger = new SensorLogger();

// Log a day of readings (5-minute intervals = 288 readings)
for (let i = 0; i < 288; i++) {
  logger.logTemperature(20 + Math.random() * 5);   // 20-25°C
  logger.logHumidity(50 + Math.random() * 10);    // 50-60%
  logger.logPressure(1013 + Math.random() * 5);   // 1013-1018 hPa
}

const size = logger.getSize();
console.log(`Stored ${size.readings} readings in ${size.bytes} bytes`);

Protocol Buffer Alternative

Use Bint as lightweight protocol:

ts
import bint from "@briklab/net-t";

class Message {
  messageType: number;
  userId: number;
  timestamp: number;
  value: number;

  constructor(type: number, userId: number, timestamp: number, value: number) {
    this.messageType = type;
    this.userId = userId;
    this.timestamp = timestamp;
    this.value = value;
  }

  serialize(): ArrayBuffer {
    const instance = bint();
    instance(this.messageType);
    instance(this.userId);
    instance(this.timestamp);
    instance(this.value);
    return instance.toBuffer();
  }

  static deserialize(buffer: ArrayBuffer): Message {
    const instance = bint.fromBuffer(buffer);
    const values = Array.from(instance.values());
    return new Message(
      values[0] as number,
      values[1] as number,
      values[2] as number,
      values[3] as number
    );
  }
}

const msg = new Message(1, 42, 1609459200, 95);
const buffer = msg.serialize();
const restored = Message.deserialize(buffer);

Next Steps