#Recovering options
orElse supplies another Option when a pipeline reaches None. Use it when a fallback should feed into the remaining steps.
#Providing a fallback with orElse
orElse takes a function with no parameters. It calls that function for a None and returns the fallback Option. A Some passes through without calling the function:
import { import Option Option } from "byenull";
const const recovered: Option.Option<string> recovered = import Option Option .function pipe<Option.Option<never>, Option.Option<string>>(a: Option.Option<never>, ab: (a: Option.Option<never>) => 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 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 orElse<() => Option.Option<string>>(fn: () => Option.Option<string>): <O1>(option: O1) => Option.OptionFor<Option.Option<string> | O1, string | Option.InferSome<O1>>Chains a fallback computation for an
Option
or
OptionAsync
.
If the input is a
Some
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The fallback function type.@exampleNone Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.orElse(() => Option.some('default')),
);
// { type: 'Some', value: 'default' }
@exampleSome Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.some('value'),
Option.orElse(() => Option.some('default')),
);
// { type: 'Some', value: 'value' }
@seeunwrap - For returning a plain value instead of a fallback Option.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators orElse (() => 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 ("fallback")),
);
// { type: 'Some', value: 'fallback' }
const const unchanged: Option.Option<string> unchanged = import Option Option .function pipe<Option.Option<string>, Option.Option<string>>(a: Option.Option<string>, ab: (a: Option.Option<string>) => 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 ("value"),
import Option Option .function orElse<() => Option.Option<string>>(fn: () => Option.Option<string>): <O1>(option: O1) => Option.OptionFor<Option.Option<string> | O1, string | Option.InferSome<O1>>Chains a fallback computation for an
Option
or
OptionAsync
.
If the input is a
Some
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The fallback function type.@exampleNone Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.orElse(() => Option.some('default')),
);
// { type: 'Some', value: 'default' }
@exampleSome Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.some('value'),
Option.orElse(() => Option.some('default')),
);
// { type: 'Some', value: 'value' }
@seeunwrap - For returning a plain value instead of a fallback Option.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators orElse (() => 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 ("fallback")),
);
// { type: 'Some', value: 'value' }, the fallback is not calledThe fallback must be an Option or OptionAsync, not a plain value.
#Trying fallback sources
A cache miss can fall back to a default source. Because orElse returns an Option, later transformations still run:
import { import Option Option } from "byenull";
const const cache: Map<string, string> cache = new var Map: MapConstructor
new <string, string>(iterable?: Iterable<readonly [string, string]> | null | undefined) => Map<string, string> (+3 overloads)
Map <string, string>();
const const defaults: Map<string, string> defaults = new var Map: MapConstructor
new <string, string>(iterable?: Iterable<readonly [string, string]> | null | undefined) => Map<string, string> (+3 overloads)
Map ([["theme", "light"]]);
const const readCache: (key: string) => Option.Option<string> readCache = import Option Option .function fn<(key: string) => string | undefined>(fn: (key: string) => string | undefined): (key: string) => Option.Option<string> (+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 ((key: string key : string) => const cache: Map<string, string> cache .Map<string, string>.get(key: string): string | undefinedReturns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
@returnsReturns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. get (key: string key ));
const const readDefault: (key: string) => Option.Option<string> readDefault = import Option Option .function fn<(key: string) => string | undefined>(fn: (key: string) => string | undefined): (key: string) => Option.Option<string> (+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 ((key: string key : string) => const defaults: Map<string, string> defaults .Map<string, string>.get(key: string): string | undefinedReturns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
@returnsReturns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. get (key: string key ));
const const theme: Option.Option<string> theme = import Option Option .function pipe<Option.Option<string>, Option.Option<string>, Option.Option<string>>(a: Option.Option<string>, ab: (a: Option.Option<string>) => Option.Option<string>, bc: (b: Option.Option<string>) => 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 (
const readCache: (key: string) => Option.Option<string> readCache ("theme"),
import Option Option .function orElse<() => Option.Option<string>>(fn: () => Option.Option<string>): <O1>(option: O1) => Option.OptionFor<Option.Option<string> | O1, string | Option.InferSome<O1>>Chains a fallback computation for an
Option
or
OptionAsync
.
If the input is a
Some
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The fallback function type.@exampleNone Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.orElse(() => Option.some('default')),
);
// { type: 'Some', value: 'default' }
@exampleSome Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.some('value'),
Option.orElse(() => Option.some('default')),
);
// { type: 'Some', value: 'value' }
@seeunwrap - For returning a plain value instead of a fallback Option.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators orElse (() => const readDefault: (key: string) => Option.Option<string> readDefault ("theme")),
import Option Option .function map<Option.Option<string>, string>(fn: (a: string) => string): (option: Option.Option<string>) => 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 ((theme: string theme ) => theme: string theme .String.toUpperCase(): stringConverts all the alphabetic characters in a string to uppercase.
toUpperCase ()),
);
// { type: 'Some', value: 'LIGHT' }Only the missing cache entry triggers orElse. If the cache contains a theme, readDefault is not called.
#Using asynchronous fallbacks
The fallback function can return an OptionAsync. orElse also waits for Promise-based input before deciding whether recovery is needed:
import { import Option Option } from "byenull";
const const theme: Option.Option<string> theme = await import Option Option .function pipe<Option.Option<never>, Option.OptionAsync<string>, Option.OptionAsync<string>>(a: Option.Option<never>, ab: (a: Option.Option<never>) => Option.OptionAsync<string>, bc: (b: Option.OptionAsync<string>) => 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 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 orElse<() => Option.OptionAsync<string>>(fn: () => Option.OptionAsync<string>): <O1>(option: O1) => Option.OptionFor<Option.OptionAsync<string> | O1, string | Option.InferSome<O1>>Chains a fallback computation for an
Option
or
OptionAsync
.
If the input is a
Some
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The fallback function type.@exampleNone Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.orElse(() => Option.some('default')),
);
// { type: 'Some', value: 'default' }
@exampleSome Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.some('value'),
Option.orElse(() => Option.some('default')),
);
// { type: 'Some', value: 'value' }
@seeunwrap - For returning a plain value instead of a fallback Option.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators orElse (() => import Option Option .function maybe<() => Promise<string>>(fn: () => Promise<string>): Option.OptionAsync<string> (+1 overload)Executes a function and wraps its result in an
Option
or
OptionAsync
.
Nullish values and Promise rejections produce
None
; synchronous throws are not captured.
@typeParamF - The function type to execute.@returnsAn Option or OptionAsync wrapping the function's return value.@exampleSynchronous Thunk
import { Option } from 'byenull';
const option = Option.maybe(() => document.querySelector('#app'));
// { type: 'Some', value: HTMLElement } or { type: 'None' }
@exampleAsynchronous Thunk
import { Option } from 'byenull';
type Config = { host: string };
const option = await Option.maybe(() =>
fetch('/api/config').then((response) => response.json() as Promise<Config>),
);
// { type: 'Some', value: Config }
@seefn - For wrapping functions that take parameters.@categoryCreators maybe (async () => "dark")),
import Option Option .function map<Option.OptionAsync<string>, string>(fn: (a: string) => string): (option: Option.OptionAsync<string>) => 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 ((theme: string theme ) => theme: string theme .String.toUpperCase(): stringConverts all the alphabetic characters in a string to uppercase.
toUpperCase ()),
);
// { type: 'Some', value: 'DARK' }Here maybe wraps the asynchronous fallback. A nullish resolution or Promise rejection would become None.
#Choosing between orElse and unwrap
orElse recovers with another Option and keeps the pipeline open. unwrap recovers with a plain default value and ends the pipeline. It never throws for a None.
Use orElse while more Option steps remain to be available. Use unwrap when the caller needs a plain value.