Skip to content

@smitejs/fp ​

Small functional programming primitives for Smite applications and framework code.

bash
yarn add @smitejs/fp

29 documented symbols · version 2.0.0-SNAPSHOT.0 · source

Composition ​

constcompositionMetadata ​

ts
const compositionMetadata: unique symbol;

Metadata symbol attached to composed functions created by flow.

The property is non-enumerable, so normal runtime iteration and serialization ignore it. Compiler and registry tooling can opt in by reading this symbol directly.

packages/fp/src/index.ts:8

interfaceCompositionMetadata ​

ts
interface CompositionMetadata {
    readonly kind: "fp.flow";
    readonly steps: readonly CompositionStep[];
}

Compile-time friendly metadata for a composed function.

packages/fp/src/index.ts:31

interfaceCompositionStep ​

ts
interface CompositionStep {
    readonly name: string;
    readonly index: number;
}

Describes a single function in a composed pipeline.

packages/fp/src/index.ts:21

functionflow ​

ts
function flow<Value>(): FlowFunction<Value, Value>;

function flow<Value, A>(a: Unary<Value, A>): FlowFunction<Value, A>;

function flow<Value, A, B>(a: Unary<Value, A>, b: Unary<A, B>): FlowFunction<Value, B>;

function flow<Value, A, B, C>(a: Unary<Value, A>, b: Unary<A, B>, c: Unary<B, C>): FlowFunction<Value, C>;

function flow<Value, A, B, C, D>(a: Unary<Value, A>, b: Unary<A, B>, c: Unary<B, C>, d: Unary<C, D>): FlowFunction<Value, D>;

function flow<Value, A, B, C, D, E>(a: Unary<Value, A>, b: Unary<A, B>, c: Unary<B, C>, d: Unary<C, D>, e: Unary<D, E>): FlowFunction<Value, E>;

function flow<Value, A, B, C, D, E, F>(a: Unary<Value, A>, b: Unary<A, B>, c: Unary<B, C>, d: Unary<C, D>, e: Unary<D, E>, f: Unary<E, F>): FlowFunction<Value, F>;

Composes unary functions from left to right.

The returned function carries non-enumerable composition metadata that can be consumed by compile-time tooling without changing runtime behavior.

ts
const validate = (value: string) => value.trim();
const normalize = (value: string) => value.toLowerCase();
const persist = (value: string) => ({ name: value });

const createUser = flow(validate, normalize, persist);
ts
{ name: "ada" }
ts
const validate = (value: string) => value.trim();
const normalize = (value: string) => value.toLowerCase();
const persist = (value: string) => ({ name: value });

const createUser = flow(validate, normalize, persist);
const metadata = getCompositionMetadata(createUser);
ts
{
  kind: "fp.flow",
  steps: [
    { index: 0, name: "validate" },
    { index: 1, name: "normalize" },
    { index: 2, name: "persist" },
  ],
}
[]
metadata

packages/fp/src/index.ts:124

typeFlowFunction ​

ts
type FlowFunction<Input, Output> = Unary<Input, Output> & {
    readonly [compositionMetadata]?: CompositionMetadata;
};

Function value returned by flow.

packages/fp/src/index.ts:41

constgetCompositionMetadata ​

ts
const getCompositionMetadata: (fn: unknown) => CompositionMetadata | undefined;

Reads composition metadata from a function when it was created by flow.

packages/fp/src/index.ts:195

functionpipe ​

ts
function pipe<Value>(value: Value): Value;

function pipe<Value, A>(value: Value, a: Unary<Value, A>): A;

function pipe<Value, A, B>(value: Value, a: Unary<Value, A>, b: Unary<A, B>): B;

function pipe<Value, A, B, C>(value: Value, a: Unary<Value, A>, b: Unary<A, B>, c: Unary<B, C>): C;

function pipe<Value, A, B, C, D>(value: Value, a: Unary<Value, A>, b: Unary<A, B>, c: Unary<B, C>, d: Unary<C, D>): D;

function pipe<Value, A, B, C, D, E>(value: Value, a: Unary<Value, A>, b: Unary<A, B>, c: Unary<B, C>, d: Unary<C, D>, e: Unary<D, E>): E;

function pipe<Value, A, B, C, D, E, F>(value: Value, a: Unary<Value, A>, b: Unary<A, B>, c: Unary<B, C>, d: Unary<C, D>, e: Unary<D, E>, f: Unary<E, F>): F;

Applies a value to a sequence of unary functions.

ts
const output = pipe(
  " smite ",
  (value) => value.trim(),
  (value) => value.toUpperCase(),
);
ts
"SMITE"

packages/fp/src/index.ts:74

Either ​

classEither ​

ts
class Either<Left, Right> {
    private readonly state;
    private constructor();
    static left<Left, Right = never>(value: Left): Either<Left, Right>;
    static right<Right, Left = never>(value: Right): Either<Left, Right>;
    isLeft(): boolean;
    isRight(): boolean;
    map<Next>(mapper: Unary<Right, Next>): Either<Left, Next>;
    flatMap<Next, NextLeft = never>(mapper: Unary<Right, Either<NextLeft, Next>>): Either<Left | NextLeft, Next>;
    mapLeft<NextLeft>(mapper: Unary<Left, NextLeft>): Either<NextLeft, Right>;
    unwrapOr(fallback: Right): Right;
}

Represents a value that is either left or right.

ts
const output = Either.right("5")
  .map(Number)
  .map((value) => value * 2)
  .mapLeft(() => "not-a-number")
  .unwrapOr(0);
ts
10

packages/fp/src/index.ts:278

Extraction ​

functionchain ​

ts
function chain<Source, Value>(...extractors: readonly Extractor<Source, Value>[]): Extractor<Source, Value>;

Tries extractors in order and returns the first value found.

Order matters: prefer more secure or more specific sources first. If every extractor misses, the result is Option.none.

The returned extractor carries chain metadata describing every nested extractor.

ts
const sessionId = chain(cookie("session_id"), header("x-session-id"));

const fromCookie = sessionId({
  cookies: { session_id: "abc123" },
  headers: {},
});
const fromHeader = sessionId({
  cookies: {},
  headers: { "x-session-id": "header-id" },
});
const missing = sessionId({ cookies: {}, headers: {} });
ts
"abc123"
"header-id"
true

packages/fp/src/index.ts:794

interfaceExtractor ​

ts
interface Extractor<Source, Value = string> {
    (source: Source): Option<Value>;
    readonly [extractorMetadata]?: ExtractorMetadata;
}

Function that reads an optional value from a source.

Transport builders such as http.cookie produce extractors specialized to their execution source. Extractors may carry non-enumerable metadata that tooling can inspect without executing the extractor.

ts
const extract = (source: HttpLike) =>
  Option.fromNullable(source.cookies.session_id);

const value = extract({ cookies: { session_id: "abc123" }, headers: {} });
ts
"abc123"
"missing",

packages/fp/src/index.ts:779

constextractorMetadata ​

ts
const extractorMetadata: unique symbol;

Metadata symbol attached to extractors created by chain or transport extractor factories.

The property is non-enumerable, so normal runtime iteration and serialization ignore it. Compiler and registry tooling can opt in by reading this symbol directly.

packages/fp/src/index.ts:738

interfaceExtractorMetadata ​

ts
interface ExtractorMetadata {
    readonly kind: "fp.extractor";
    readonly source: ExtractorSource;
    readonly key: string;
    readonly chain?: readonly ExtractorMetadata[];
}

Compile-time friendly metadata for an extractor.

packages/fp/src/index.ts:767

typeExtractorSource ​

ts
type ExtractorSource = "authHeader" | "chain" | "cookie" | "custom" | "form" | "header" | "param" | "query";

Identifies where an extractor reads its value.

packages/fp/src/index.ts:752

constgetExtractorMetadata ​

ts
const getExtractorMetadata: (fn: unknown) => ExtractorMetadata | undefined;

Reads extractor metadata from a function when it carries any.

ts
const read = (source: HttpLike) =>
  Option.fromNullable(source.headers["x-id"]);
const extractor = chain(read);
const metadata = getExtractorMetadata(extractor);
ts
{
  kind: "fp.extractor",
  source: "chain",
  key: "read",
  chain: [
    {
      kind: "fp.extractor",
      source: "custom",
      key: "read",
    },
  ],
}
[]
metadata

packages/fp/src/index.ts:835

Function Utilities ​

constconstant ​

ts
const constant: <Value>(value: Value) => (() => Value);

Creates a function that always returns the same value.

packages/fp/src/index.ts:57

constidentity ​

ts
const identity: <Value>(value: Value) => Value;

Returns the input unchanged.

packages/fp/src/index.ts:50

constnoop ​

ts
const noop: () => void;

Function that intentionally does nothing.

packages/fp/src/index.ts:67

Match ​

constMatcher ​

ts
const Matcher: Readonly<{
    from: <Value, ErrorValue>(result: Result<Value, ErrorValue>) => ResultMatcher<Value, ErrorValue, never, never>;
}>;

Fluent matcher entry point.

ts
const output = Matcher.from(Result.err("missing-name"))
  .ok((name) => `created:${name}`)
  .err((error) => `recovered:${error}`)
  .run();
ts
"recovered:missing-name"

packages/fp/src/index.ts:606

Option ​

classOption ​

ts
class Option<Value> {
    private readonly state;
    private constructor();
    static some<Value>(value: Value): Option<Value>;
    static none<Value = never>(): Option<Value>;
    static fromNullable<Value>(value: Value | null | undefined): Option<Value>;
    isSome(): boolean;
    isNone(): boolean;
    map<Next>(mapper: Unary<Value, Next>): Option<Next>;
    flatMap<Next>(mapper: Unary<Value, Option<Next>>): Option<Next>;
    filter(predicate: Predicate<Value>): Option<Value>;
    tap(effect: Unary<Value, void>): Option<Value>;
    unwrapOr(fallback: Value): Value;
    unwrapOrElse(fallback: () => Value): Value;
}

Optional value without null or undefined control flow.

ts
const name = Option.fromNullable(" Ada ")
  .map((value) => value.trim())
  .filter((value) => value.length > 0)
  .unwrapOr("anonymous");
ts
"Ada"
"anonymous",

packages/fp/src/index.ts:210

Predicate ​

constand ​

ts
const and: <Value>(...predicates: readonly Predicate<Value>[]) => Predicate<Value>;

Creates a predicate that requires every predicate to pass.

ts
const isNonEmptyString = and(
  isString,
  not((value: string) => value === ""),
);

const valid = isNonEmptyString("smite");
ts
true
true

packages/fp/src/index.ts:656

constisEmpty ​

ts
const isEmpty: (value: unknown) => boolean;

Checks whether a value is empty.

Empty values are empty strings, empty arrays, empty maps, empty sets and objects without enumerable keys.

packages/fp/src/index.ts:714

constisNumber ​

ts
const isNumber: (value: unknown) => value is number;

Checks whether a value is a number that is not NaN.

packages/fp/src/index.ts:695

constisString ​

ts
const isString: (value: unknown) => value is string;

Checks whether a value is a string.

packages/fp/src/index.ts:687

constisUUID ​

ts
const isUUID: (value: unknown) => value is string;

Checks whether a string is a UUID.

packages/fp/src/index.ts:703

constnot ​

ts
const not: <Value>(predicate: Predicate<Value>) => Predicate<Value>;

Negates a predicate.

packages/fp/src/index.ts:677

constor ​

ts
const or: <Value>(...predicates: readonly Predicate<Value>[]) => Predicate<Value>;

Creates a predicate that requires at least one predicate to pass.

packages/fp/src/index.ts:667

Result ​

classResult ​

ts
class Result<Value, ErrorValue = Error> {
    private readonly state;
    private constructor();
    static ok<Value, ErrorValue = never>(value: Value): Result<Value, ErrorValue>;
    static err<ErrorValue, Value = never>(error: ErrorValue): Result<Value, ErrorValue>;
    static err<Tag, Data>(tag: Tag, data: Data): Result<never, {
        readonly tag: Tag;
        readonly data: Data;
    }>;
    static fromThrowable<Value, ErrorValue = unknown>(operation: () => Value, mapError?: Unary<unknown, ErrorValue>): Result<Value, ErrorValue>;
    isOk(): boolean;
    isErr(): boolean;
    map<Next>(mapper: Unary<Value, Next>): Result<Next, ErrorValue>;
    flatMap<Next, NextError = never>(mapper: Unary<Value, Result<Next, NextError>>): Result<Next, ErrorValue | NextError>;
    mapErr<NextError>(mapper: Unary<ErrorValue, NextError>): Result<Value, NextError>;
    recover(mapper: Unary<ErrorValue, Value>): Result<Value, never>;
    tap(effect: Unary<Value, void>): Result<Value, ErrorValue>;
    tapErr(effect: Unary<ErrorValue, void>): Result<Value, ErrorValue>;
    unwrapOr(fallback: Value): Value;
    unwrapOrElse(fallback: Unary<ErrorValue, Value>): Value;
    match<OkOutput, ErrOutput>(ok: Unary<Value, OkOutput>, err: Unary<ErrorValue, ErrOutput>): OkOutput | ErrOutput;
}

Success or failure without exception-driven control flow.

ts
const saveUser = (name: string) =>
  name.length > 0 ? Result.ok({ name }) : Result.err("missing-name");

const user = Result.ok(" Ada ")
  .map((value) => value.trim())
  .flatMap(saveUser)
  .recover(() => ({ name: "anonymous" }))
  .tap(({ name }) => name.toLowerCase())
  .unwrapOr({ name: "fallback" });
ts
{ name: "Ada" }

packages/fp/src/index.ts:332

Task ​

classTask ​

ts
class Task<Value> {
    private readonly operation;
    private constructor();
    static from<Value>(operation: () => MaybePromise<Value>): Task<Value>;
    static of<Value>(value: Value): Task<Value>;
    map<Next>(mapper: Unary<Value, MaybePromise<Next>>): Task<Next>;
    flatMap<Next>(mapper: Unary<Value, Task<Next>>): Task<Next>;
    tap(effect: Unary<Value, MaybePromise<void>>): Task<Value>;
    run(): Promise<Value>;
}

Lazy asynchronous computation.

ts
const task = Task.from(async () => "Ada")
  .map((name) => name.toLowerCase())
  .tap(() => {
    runs += 1;
  });
ts
0
"ada"
1

packages/fp/src/index.ts:459

TaskResult ​

classTaskResult ​

ts
class TaskResult<Value, ErrorValue = Error> {
    private readonly task;
    private constructor();
    static ok<Value, ErrorValue = never>(value: Value): TaskResult<Value, ErrorValue>;
    static err<ErrorValue, Value = never>(error: ErrorValue): TaskResult<Value, ErrorValue>;
    static fromResult<Value, ErrorValue>(result: Result<Value, ErrorValue>): TaskResult<Value, ErrorValue>;
    static from<Value, ErrorValue = unknown>(operation: () => MaybePromise<Value>, mapError?: Unary<unknown, ErrorValue>): TaskResult<Value, ErrorValue>;
    map<Next>(mapper: Unary<Value, MaybePromise<Next>>): TaskResult<Next, ErrorValue>;
    flatMap<Next, NextError = never>(mapper: Unary<Value, TaskResult<Next, NextError>>): TaskResult<Next, ErrorValue | NextError>;
    mapErr<NextError>(mapper: Unary<ErrorValue, NextError>): TaskResult<Value, NextError>;
    recover(mapper: Unary<ErrorValue, MaybePromise<Value>>): TaskResult<Value, never>;
    tap(effect: Unary<Value, MaybePromise<void>>): TaskResult<Value, ErrorValue>;
    run(): Promise<Result<Value, ErrorValue>>;
}

Lazy asynchronous computation that resolves to a Result.

ts
const task = TaskResult.from(async () => " Ada ")
  .map((value) => value.trim())
  .flatMap((value) =>
    value.length > 0 ? TaskResult.ok(value) : TaskResult.err("empty"),
  )
  .recover(() => "anonymous");

const result = await task.run();
ts
"Ada"

packages/fp/src/index.ts:497

Released under the MIT License.

/ search•[ ] prev/next•j/k scroll•h home•t theme•api/smitejs-fp