The constant function of one parameter: will always return the value you give, no matter the parameter it's given.
Take a no-parameter partial function (may return undefined or throw), and lift it to return an Either instead.
Note that unlike the Function0Static.liftOption version, if the function returns undefined, the liftEither version will throw (the liftOption version returns None()): if you want to do pure side-effects which may throw, you're better off just using javascript try blocks.
When using typescript, to help the compiler infer the left type,
you can either pass a second parameter like {} as <type>
, or
call with try_<L,R>(...)
.
const eitherRand = Function0.liftEither(Math.random, {} as string);
eitherRand();
=> Either.right(0.49884723907769635)
const undef = Function0.liftEither(() => undefined);
undef();
=> throws
const throws = Function0.liftEither(() => {throw "x"});
throws();
=> Either.left("x")
Also see EitherStatic.try_
Take a no-parameter partial function (may return null, undefined or throw), and lift it to return an Option instead. null and undefined become a None, everything else a Some
const randOpt = Function0.liftNullable(Math.random);
randOpt();
=> Option.of(0.49884723907769635)
const undef = Function0.liftNullable(()=>undefined);
undef();
=> Option.none()
const nl = Function0.liftNullable(()=>null);
nl();
=> Option.none()
const throws = Function0.liftNullable(()=>{throw "x"});
throws();
=> Option.none()
Also see Function0Static.liftOption, OptionStatic.try_ and OptionStatic.tryNullable
Take a no-parameter partial function (may return undefined or throw), and lift it to return an Option instead. undefined becomes a None, everything else a Some
const randOpt = Function0.liftOption(Math.random);
randOpt();
=> Option.of(0.49884723907769635)
const undef = Function0.liftOption(()=>undefined);
undef();
=> Option.none()
const nl = Function0.liftOption(()=>null);
nl();
=> Option.of(null)
const throws = Function0.liftOption(()=>{throw "x"});
throws();
=> Option.none()
Also see Function0Static.liftNullable, OptionStatic.try_ and OptionStatic.tryNullable
Take a one-parameter function and lift it to become a Function1Static, enabling you to call Function1.andThen and other such methods on it.
Generated using TypeDoc
This is the type of the Function0 constant, which offers some helper functions to deal with Function0 including the ability to build Function0 from functions using Function0Static.of. It also offers some builtin functions like Function0Static.constant.