refine<TUnrefined, TRefined, TArgs extends unknown[] = []>(coder: Coder<TUnrefined>,refiner: Refiner<TUnrefined, TRefined, TArgs>): (...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.
Example 1
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());
coder: Coder<TUnrefined>
The base coder to refine
refiner: Refiner<TUnrefined, TRefined, TArgs>
The refiner that defines the transformation logic