Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Created January 18, 2025 20:26
Show Gist options
  • Save colelawrence/080ab1a95cf29116d88a396e2739c834 to your computer and use it in GitHub Desktop.
Save colelawrence/080ab1a95cf29116d88a396e2739c834 to your computer and use it in GitHub Desktop.
Like a pipe function, but early return if any function returns a null-ish value
type Fn<T, U> = (t: T) => U | null | undefined;
/** like pipe, but returns early if any of the functions return a nullish value */
export function pipeNonNull<A, B>(a: A, b: Fn<A, B>): B | null | undefined;
export function pipeNonNull<A, B, C>(a: A, b: Fn<A, B>, c: Fn<B, C>): C | null | undefined;
export function pipeNonNull<A, B, C, D>(a: A, b: Fn<A, B>, c: Fn<B, C>, d: Fn<C, D>): D | null | undefined;
export function pipeNonNull<A, B, C, D, E>(a: A, b: Fn<A, B>, c: Fn<B, C>, d: Fn<C, D>, e: Fn<D, E>): E | null | undefined;
export function pipeNonNull<A, B, C, D, E, F>(
a: A,
b: Fn<A, B>,
c: Fn<B, C>,
d: Fn<C, D>,
e: Fn<D, E>,
f: Fn<E, F>): F | null | undefined;
export function pipeNonNull<A, B, C, D, E, F, G>(
a: A,
b: Fn<A, B>,
c: Fn<B, C>,
d: Fn<C, D>,
e: Fn<D, E>,
f: Fn<E, F>,
g: Fn<F, G>): G | null | undefined;
// Single implementation signature
export function pipeNonNull(a: unknown, ...fns: Array<Fn<unknown, unknown>>): unknown {
let current = a;
for (let i = 0; i < fns.length; i++) {
if (current == null) {
// If we've already hit null or undefined, just return it
return current;
}
current = fns[i](current);
}
return current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment