import { decoder } from "https://deno.land/x/fun@v2.0.0/mod.ts";
const { lazy } = decoder;
The Lazy decoder combinator allows for the creation of recursive or mutually recursive decoding. The passed decoder thunk is memoized to keep the vm from falling into an infinite loop.
Examples
Example 1
Example 1
import type { Decoder } from "./decoder.ts";
import * as D from "./decoder.ts";
import { pipe } from "./fn.ts";
type Person = { name: string; age: number; children: ReadonlyArray<Person> };
const person = (
name: string,
age: number,
children: ReadonlyArray<Person> = []
): Person => ({ name, age, children });
const decode: Decoder<unknown, Person> = D.lazy(
"Person",
() => D.struct({ name: D.string, age: D.number, children: D.array(decode) }),
);
const rufus = person("Rufus", 1);
const brandon = person("Brandon", 37, [rufus]);
const jackie = person("Jackie", 57, [brandon]);
const result1 = decode(null); // Left(DecodeError)
const result2 = decode(rufus); // Right(rufus)
const result3 = decode(brandon); // Right(brandon)
const result4 = decode(jackie); // Right(jackie)