import { optic } from "https://deno.land/x/fun@v2.0.0/mod.ts";
const { prism } = optic;
Construct a Prism<S, A> from view and review functions, with an optional modify function that will be defaulted if not provided.
Examples
Example 1
Example 1
import * as O from "./optic.ts";
import * as Op from "./option.ts";
const key = (key: string) => <A>() =>
O.prism<Record<string, A>, A>(
rec => Op.fromNullable(rec[key]),
a => ({ [key]: a }),
mod => s => Object.hasOwn(s, key) ? ({ ...s, [key]: mod(s[key]) }) : s,
);
const atFoo = key("foo")<number>();
const result1 = atFoo.view({ bar: 1 }); // None
const result2 = atFoo.view({ foo: 2 }); // Some(2)
const result3 = atFoo.review(5); // { foo: 5 }
const result4 = atFoo.modify(n => n + 1)({ bar: 1 }); // { bar: 1 }
const result5 = atFoo.modify(n => n + 1)({ foo: 1 }); // { foo: 2 }
const result6 = atFoo.modify(n => n + 1)({ foo: 1, bar: 2 });
// { foo: 2, bar: 2 }