Skip to main content
Module

x/fun/mod.ts>decoder.fromPredicate

A collection of algebraic data types, lenses, and schemables based on a light weight higher kinded type implementation. Written for deno.
Latest
function decoder.fromPredicate
import { decoder } from "https://deno.land/x/fun@v2.0.0/mod.ts";
const { fromPredicate } = decoder;

Construct a Decoder<A, A> from a Predicate and a reason for failure or a Decoder<A, B> from a Refinement<A, B> and a reason for failure. While decoding, the value A is passed to the predicate/refinement. If it returns true then the result is wrapped in Success, otherwise the value and reason are wrapped in Failure.

Examples

Example 1

import * as D from "./decoder.ts";
import * as R from "./refinement.ts";
import { pipe } from "./fn.ts";

const nonEmpty = D.fromPredicate(
  (s: string) => s.length > 0, // Predicate
  "noninit string"
);
const string = D.fromPredicate(R.string, "string");
const nonEmptyString = pipe(
  string,
  D.compose(nonEmpty),
);

const result1 = nonEmptyString(null); // Left(DecodeError)
const result2 = nonEmptyString(""); // Left(DecodeError)
const result3 = nonEmptyString("Hello"); // Right("Hello")

Type Parameters

B
A extends B

Parameters

guard: Refinement<B, A>
expected: string

Type Parameters

B
A extends B

Parameters

guard: Predicate<A>
expected: string