#Pipe basics
In this chapter we will rewire our profile lookup as a pipeline. pipe is the heart of byenull: it connects multiple operations into a single, readable flow that runs from top to bottom.
#What is pipe?
pipe takes an initial value and passes it through a series of functions.
Each function receives the output of the previous one:
import { import Option Option } from "byenull";
const const result: string result = import Option Option .function pipe<number, number, number, string>(a: number, ab: (a: number) => number, bc: (b: number) => number, cd: (c: number) => string): string (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 25 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Option } from 'byenull';
const result = Option.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
5, // Start with 5
(x: number x ) => x: number x + 1, // 5 + 1 = 6
(x: number x ) => x: number x * 2, // 6 * 2 = 12
(x: number x ) => `Result: ${x: number x }`, // 'Result: 12'
);
// 'Result: 12'pipe is a general utility. It works with any unary functions, not just byenull's.
Since byenull is designed to interop with @praha/byethrow, we can use Result.pipe everywhere we use Option.pipe. In fact, they are exactly the same functions. It's recommended to use either one exclusively.
#Why use pipe?
Without pipe, we either nest function calls, which must be read from the inside out:
// ❌ Hard to read: inside out
const const result: string result = const format: (x: number) => string format (const double: (x: number) => number double (const addOne: (x: number) => number addOne (5)));Or we introduce intermediate variables, which is verbose:
// ❌ Verbose: too many variables
const const step1: number step1 = const addOne: (x: number) => number addOne (5);
const const step2: number step2 = const double: (x: number) => number double (const step1: number step1 );
const const result: string result = const format: (x: number) => string format (const step2: number step2 );With pipe, the steps are listed in the order they run:
import { import Option Option } from "byenull";
// ✅ Clear: top to bottom
const const result: string result = import Option Option .function pipe<5, number, number, string>(a: 5, ab: (a: 5) => number, bc: (b: number) => number, cd: (c: number) => string): string (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 25 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Option } from 'byenull';
const result = Option.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
5,
const addOne: (x: number) => number addOne ,
const double: (x: number) => number double ,
const format: (x: number) => string format
);#Using pipe with Options
The real power shows when the value is an Option.
Functions such as Option.map are curried: calling them with a callback returns a function that takes an Option, exactly what pipe expects:
import { import Option Option } from "byenull";
type type User = {
id: string;
name: string;
}
User = { id: string id : string; name: string name : string };
const const findUser: (id: string, users: User[]) => Option.Option<User> findUser = import Option Option .function fn<(id: string, users: User[]) => User | undefined>(fn: (id: string, users: User[]) => User | undefined): (id: string, users: User[]) => Option.Option<User> (+1 overload)Wraps a function and returns a new function that returns an
Option
or
OptionAsync
.
Nullish values and Promise rejections produce
None
; synchronous throws are not captured.
@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@exampleSynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);
findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@exampleAsynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});
await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators fn ((id: string id : string, users: User[] users : type User = {
id: string;
name: string;
}
User []) =>
users: User[] users .Array<User>.find(predicate: (value: User, index: number, obj: User[]) => unknown, thisArg?: any): User | undefined (+1 overload)Returns the value of the first element in the array where predicate is true, and undefined
otherwise.
@parampredicate find calls predicate once for each element of the array, in ascending
order, until it finds one where predicate returns true. If such an element is found, find
immediately returns that element value. Otherwise, find returns undefined.@paramthisArg If provided, it will be used as the this value for each invocation of
predicate. If it is not provided, undefined is used instead. find ((user: User user ) => user: User user .id: string id === id: string id )
);
const const users: User[] users : type User = {
id: string;
name: string;
}
User [] = [{ id: string id : "u1", name: string name : "Alice" }];
const const option: Option.Option<string> option = import Option Option .function pipe<Option.Option<string>, Option.Option<User>, Option.Option<string>>(a: Option.Option<string>, ab: (a: Option.Option<string>) => Option.Option<User>, bc: (b: Option.Option<User>) => Option.Option<string>): Option.Option<string> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 25 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Option } from 'byenull';
const result = Option.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Option Option .function some<string>(value: string): Option.Option<string>Creates a
Some
from a given value.
Passing null or undefined returns
None
instead.
@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@exampleimport { Option } from 'byenull';
const some = Option.some(42);
// { type: 'Some', value: 42 }
const none = Option.some(null);
// { type: 'None' }
@categoryCreators some ("u1"),
import Option Option .function andThen<(id: any) => Option.Option<User>>(fn: (id: any) => Option.Option<User>): <O1>(option: O1) => Option.OptionFor<Option.Option<User> | O1, User> (+1 overload)Chains the next computation using the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The function type to chain.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@exampleNone Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@exampleAsynchronous Case
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);
const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen ((id: any id ) => const findUser: (id: string, users: User[]) => Option.Option<User> findUser (id: any id , const users: User[] users )),
import Option Option .function map<Option.Option<User>, string>(fn: (a: User) => string): (option: Option.Option<User>) => Option.Option<string> (+1 overload)Applies a transformation function to the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
@typeParamO - The input Option or OptionAsync.@typeParamU - The transformed value type.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.map((x) => x * 10),
);
// { type: 'Some', value: 20 }
@exampleNone Case (unchanged)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.map((x: number) => x * 10),
);
// { type: 'None' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map ((user: User user ) => user: User user .name: string name ),
);
// { type: 'Some', value: 'Alice' }#A None short-circuits the pipeline
Each function only runs its callback when there is a value to work with.
Once a step comes up empty, the following value-side steps are skipped and the None flows straight to the end:
import { import Option Option } from "byenull";
const const option: Option.Option<number> option = import Option Option .function pipe<Option.Option<string>, Option.Option<number>, Option.Option<number>, Option.Option<number>>(a: Option.Option<string>, ab: (a: Option.Option<string>) => Option.Option<number>, bc: (b: Option.Option<number>) => Option.Option<number>, cd: (c: Option.Option<number>) => Option.Option<number>): Option.Option<number> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 25 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Option } from 'byenull';
const result = Option.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Option Option .function some<string>(value: string): Option.Option<string>Creates a
Some
from a given value.
Passing null or undefined returns
None
instead.
@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@exampleimport { Option } from 'byenull';
const some = Option.some(42);
// { type: 'Some', value: 42 }
const none = Option.some(null);
// { type: 'None' }
@categoryCreators some ("u404"),
import Option Option .function andThen<() => Option.Option<number>>(fn: () => Option.Option<number>): <O1>(option: O1) => Option.OptionFor<Option.Option<number> | O1, number> (+1 overload)Chains the next computation using the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The function type to chain.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@exampleNone Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@exampleAsynchronous Case
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);
const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen ((): import Option Option .type Option<T> = Option.Some<T> | Option.NoneA union type representing either a
Some
or a
None
.
@typeParamT - The type of the Some value.@exampleimport { Option } from 'byenull';
const doSomething = (): Option.Option<number> => {
return Math.random() > 0.5
? Option.some(10)
: Option.none();
};
@categoryCore Types Option <number> => import Option Option .function none(): Option.Option<never>Creates a
None
: an Option that holds no value.
@returnsA None.@exampleimport { Option } from 'byenull';
const option = Option.none();
// { type: 'None' }
@categoryCreators none ()),
import Option Option .function map<Option.Option<number>, number>(fn: (a: number) => number): (option: Option.Option<number>) => Option.Option<number> (+1 overload)Applies a transformation function to the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
@typeParamO - The input Option or OptionAsync.@typeParamU - The transformed value type.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.map((x) => x * 10),
);
// { type: 'Some', value: 20 }
@exampleNone Case (unchanged)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.map((x: number) => x * 10),
);
// { type: 'None' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map ((x: number x ) => x: number x * 2), // Skipped
import Option Option .function map<Option.Option<number>, number>(fn: (a: number) => number): (option: Option.Option<number>) => Option.Option<number> (+1 overload)Applies a transformation function to the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
@typeParamO - The input Option or OptionAsync.@typeParamU - The transformed value type.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.map((x) => x * 10),
);
// { type: 'Some', value: 20 }
@exampleNone Case (unchanged)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.map((x: number) => x * 10),
);
// { type: 'None' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map ((x: number x ) => x: number x + 5), // Skipped
);
// { type: 'None' }This is why we don't need to check for absence after every step. The checking from the last chapter happens once, inside the pipeline.
Notice how we got rid of if guards, nullish checks and early returns. With piping and Option, our functions can focus on the happy path and showing the business logic. We show the intent of what is supposed to happen, and we skip the steps that cannot happen if a value is missing.
#Our project as a pipeline
Here is our displayName function, rebuilt as a pipeline:
import { import Option Option } from "byenull";
type type User = {
id: string;
name: string;
}
User = { id: string id : string; name: string name : string };
type type Profile = {
userId: string;
displayName?: string;
}
Profile = { userId: string userId : string; displayName?: string | undefined displayName ?: string };
const const users: User[] users : type User = {
id: string;
name: string;
}
User [] = [
{ id: string id : "u1", name: string name : "Alice" },
{ id: string id : "u2", name: string name : "Bob" },
];
const const profiles: Profile[] profiles : type Profile = {
userId: string;
displayName?: string;
}
Profile [] = [{ userId: string userId : "u1", displayName?: string | undefined displayName : "Alice A." }];
const const findUser: (id: string, users: User[]) => Option.Option<User> findUser = import Option Option .function fn<(id: string, users: User[]) => User | undefined>(fn: (id: string, users: User[]) => User | undefined): (id: string, users: User[]) => Option.Option<User> (+1 overload)Wraps a function and returns a new function that returns an
Option
or
OptionAsync
.
Nullish values and Promise rejections produce
None
; synchronous throws are not captured.
@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@exampleSynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);
findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@exampleAsynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});
await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators fn ((id: string id : string, users: User[] users : type User = {
id: string;
name: string;
}
User []) =>
users: User[] users .Array<User>.find(predicate: (value: User, index: number, obj: User[]) => unknown, thisArg?: any): User | undefined (+1 overload)Returns the value of the first element in the array where predicate is true, and undefined
otherwise.
@parampredicate find calls predicate once for each element of the array, in ascending
order, until it finds one where predicate returns true. If such an element is found, find
immediately returns that element value. Otherwise, find returns undefined.@paramthisArg If provided, it will be used as the this value for each invocation of
predicate. If it is not provided, undefined is used instead. find ((user: User user ) => user: User user .id: string id === id: string id )
);
const const findProfile: (userId: string, profiles: Profile[]) => Option.Option<Profile> findProfile = import Option Option .function fn<(userId: string, profiles: Profile[]) => Profile | undefined>(fn: (userId: string, profiles: Profile[]) => Profile | undefined): (userId: string, profiles: Profile[]) => Option.Option<Profile> (+1 overload)Wraps a function and returns a new function that returns an
Option
or
OptionAsync
.
Nullish values and Promise rejections produce
None
; synchronous throws are not captured.
@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@exampleSynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);
findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@exampleAsynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});
await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators fn ((userId: string userId : string, profiles: Profile[] profiles : type Profile = {
userId: string;
displayName?: string;
}
Profile []) =>
profiles: Profile[] profiles .Array<Profile>.find(predicate: (value: Profile, index: number, obj: Profile[]) => unknown, thisArg?: any): Profile | undefined (+1 overload)Returns the value of the first element in the array where predicate is true, and undefined
otherwise.
@parampredicate find calls predicate once for each element of the array, in ascending
order, until it finds one where predicate returns true. If such an element is found, find
immediately returns that element value. Otherwise, find returns undefined.@paramthisArg If provided, it will be used as the this value for each invocation of
predicate. If it is not provided, undefined is used instead. find ((profile: Profile profile ) => profile: Profile profile .userId: string userId === userId: string userId ),
);
const const displayName: (id: string) => any displayName = (id: string id : string) =>
import Option Option .function pipe<Option.Option<string>, Option.Option<User>, Option.Option<Profile>, Option.Option<any>, any>(a: Option.Option<string>, ab: (a: Option.Option<string>) => Option.Option<User>, bc: (b: Option.Option<User>) => Option.Option<Profile>, cd: (c: Option.Option<Profile>) => Option.Option<any>, de: (d: Option.Option<any>) => any): any (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 25 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Option } from 'byenull';
const result = Option.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Option Option .function some<string>(value: string): Option.Option<string>Creates a
Some
from a given value.
Passing null or undefined returns
None
instead.
@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@exampleimport { Option } from 'byenull';
const some = Option.some(42);
// { type: 'Some', value: 42 }
const none = Option.some(null);
// { type: 'None' }
@categoryCreators some (id: string id ),
import Option Option .function andThen<(id: any) => Option.Option<User>>(fn: (id: any) => Option.Option<User>): <O1>(option: O1) => Option.OptionFor<Option.Option<User> | O1, User> (+1 overload)Chains the next computation using the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The function type to chain.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@exampleNone Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@exampleAsynchronous Case
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);
const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen ((id: any id ) => const findUser: (id: string, users: User[]) => Option.Option<User> findUser (id: any id , const users: User[] users )),
import Option Option .function andThen<(user: any) => Option.Option<Profile>>(fn: (user: any) => Option.Option<Profile>): <O1>(option: O1) => Option.OptionFor<Option.Option<Profile> | O1, Profile> (+1 overload)Chains the next computation using the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The function type to chain.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@exampleNone Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@exampleAsynchronous Case
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);
const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen ((user: any user ) => const findProfile: (userId: string, profiles: Profile[]) => Option.Option<Profile> findProfile (user: any user .id, const profiles: Profile[] profiles )),
import Option Option .function andThen<(profile: any) => Option.Option<any>>(fn: (profile: any) => Option.Option<any>): <O1>(option: O1) => Option.OptionFor<Option.Option<any> | O1, any> (+1 overload)Chains the next computation using the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The function type to chain.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@exampleNone Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@exampleAsynchronous Case
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);
const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen ((profile: any profile ) => import Option Option .function some<any>(value: any): Option.Option<any>Creates a
Some
from a given value.
Passing null or undefined returns
None
instead.
@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@exampleimport { Option } from 'byenull';
const some = Option.some(42);
// { type: 'Some', value: 42 }
const none = Option.some(null);
// { type: 'None' }
@categoryCreators some (profile: any profile .displayName)), // undefined becomes None
import Option Option .function unwrap<string>(defaultValue: string): <O>(option: O & ([string] extends [Option.InferSome<O> | null | undefined] ? unknown : never)) => Option.Unwrapped<O, string, Option.InferSome<O>>Extracts the value from an
Option
or
OptionAsync
.
If the input is a
None
, the default value is returned.
@typeParamD - The default value type.@exampleSome Case
import { Option } from 'byenull';
const value = Option.pipe(
Option.some(2),
Option.unwrap(0),
);
// 2
@exampleNone Case
import { Option } from 'byenull';
const empty: Option.Option<number> = Option.none();
const value = Option.pipe(
empty,
Option.unwrap(0),
);
// 0
@exampleNullish Default
import { Option } from 'byenull';
const value: number | null = Option.pipe(
Option.some(2),
Option.unwrap(null),
);
@seeorElse - For recovering with a fallback Option instead of a plain value.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryUnwraps unwrap ("unknown"),
);
const displayName: (id: string) => any displayName ("u1"); // 'Alice A.'
const displayName: (id: string) => any displayName ("u2"); // 'unknown', no profile
const displayName: (id: string) => any displayName ("u404"); // 'unknown', no userEvery step is one line, absence flows through automatically, and the fallback lives at the very end.
#Async Steps
If any step returns a Promise, the rest of the pipeline runs asynchronously and pipe returns a Promise.
We only have to await the pipe call itself:
import { import Option Option } from "byenull";
type type Avatar = {
url: string;
}
Avatar = { url: string url : string };
const const fetchAvatar: (userId: string) => Option.OptionAsync<Avatar> fetchAvatar = import Option Option .function fn<(userId: string) => Promise<Avatar | null>>(fn: (userId: string) => Promise<Avatar | null>): (userId: string) => Option.OptionAsync<Avatar> (+1 overload)Wraps a function and returns a new function that returns an
Option
or
OptionAsync
.
Nullish values and Promise rejections produce
None
; synchronous throws are not captured.
@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@exampleSynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);
findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@exampleAsynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});
await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators fn (async (userId: string userId : string) => {
const const response: Response response = await function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> fetch (`/api/avatars/${userId: string userId }`);
return const response: Response response .Body.json(): Promise<any> json () as interface Promise<T>Represents the completion of an asynchronous operation
Promise <type Avatar = {
url: string;
}
Avatar | null>;
});
const const avatarUrl: Option.Option<string> avatarUrl = await import Option Option .function pipe<Option.Option<string>, Option.OptionAsync<Avatar>, Option.OptionAsync<string>>(a: Option.Option<string>, ab: (a: Option.Option<string>) => Option.OptionAsync<Avatar>, bc: (b: Option.OptionAsync<Avatar>) => Option.OptionAsync<string>): Option.OptionAsync<string> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 25 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Option } from 'byenull';
const result = Option.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Option Option .function some<string>(value: string): Option.Option<string>Creates a
Some
from a given value.
Passing null or undefined returns
None
instead.
@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@exampleimport { Option } from 'byenull';
const some = Option.some(42);
// { type: 'Some', value: 42 }
const none = Option.some(null);
// { type: 'None' }
@categoryCreators some ("u1"),
import Option Option .function andThen<(userId: string) => Option.OptionAsync<Avatar>>(fn: (userId: string) => Option.OptionAsync<Avatar>): <O1>(option: O1) => Option.OptionFor<Option.OptionAsync<Avatar> | O1, Avatar> (+1 overload)Chains the next computation using the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The function type to chain.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@exampleNone Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@exampleAsynchronous Case
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);
const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen (const fetchAvatar: (userId: string) => Option.OptionAsync<Avatar> fetchAvatar ), // async
import Option Option .function map<Option.OptionAsync<Avatar>, string>(fn: (a: Avatar) => string): (option: Option.OptionAsync<Avatar>) => Option.OptionAsync<string> (+1 overload)Applies a transformation function to the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
@typeParamO - The input Option or OptionAsync.@typeParamU - The transformed value type.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.map((x) => x * 10),
);
// { type: 'Some', value: 20 }
@exampleNone Case (unchanged)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.map((x: number) => x * 10),
);
// { type: 'None' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map ((avatar: Avatar avatar ) => avatar: Avatar avatar .url: string url ), // receives the resolved value
);
// Option<string>