function refine
refine<TUnrefined, TRefined, TArgs extends unknown[] = []>(
coder: Coder<TUnrefined>,
): (...args: TArgs) => Coder<TRefined>

Creates a refined coder that applies transformations during encoding and decoding.

This function takes a base coder and a refiner, then returns a function that creates refined coders. The returned function accepts arguments that are passed to the refiner's encode and decode methods.

Examples

Example 1

import { assertEquals } from "@std/assert";
import { string, refine } from "@hertzg/binstruct";

// Create a refiner for date encoding/decoding
const isoDateString = refine(string(), {
  refine: (unrefined: string) => new Date(unrefined),
  unrefine: (refined: Date) => refined.toISOString(),
});

// Create a date coder that works with Unix timestamps
const dateCoder = isoDateString();

const testDate = new Date("2025-08-22T00:00:00Z");
const buffer = new Uint8Array(100);

const bytesWritten = dateCoder.encode(testDate, buffer);
const [decodedDate, bytesRead] = dateCoder.decode(buffer);

assertEquals(bytesRead, bytesWritten);
assertEquals(decodedDate.getTime(), testDate.getTime());

Type Parameters

TUnrefined

The original decoded type from the base coder

TRefined

The refined type after transformation

TArgs extends unknown[] = []

Additional arguments for the refiner

Parameters

coder: Coder<TUnrefined>

The base coder to refine

The refiner that defines the transformation logic

Return Type

(...args: TArgs) => Coder<TRefined>

A function that creates refined coders with the specified arguments

Usage

import { refine } from "refine/refine.ts";