New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@luolapeikko/result-option

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@luolapeikko/result-option - npm Package Compare versions

Comparing version 0.6.6 to 1.0.0

dist/index.cjs.map

745

dist/index.d.ts

@@ -1,65 +0,1 @@

/**
* Interface for the And method
*/
interface IAnd<BaseType, OutType extends BaseType> {
/**
* and method, returns the second value if the result is true, otherwise returns the this error or the second error depending on the self value in that order
*
* @see https://doc.rust-lang.org/std/result/enum.Result.html#method.and
* @param {Result} value - compare value
* @returns {Result} - Result based on the self value and the value parameter
* @example
* Err<number>(new Error('broken')).and(Ok<number>(3)) // Err<number>(new Error('broken'))
* Ok<number>(2).and(Err<number>(new Error('broken'))) // Err<number>(new Error('broken'))
* Ok<number>(2).and(Ok<number>(3)) // Ok<number>(3)
*/
and<CompareType extends BaseType>(value: CompareType): OutType | CompareType;
}
interface IAndThen<ValueType, ContainerType, FalseType extends ContainerType> {
/**
* and then method, if true result use the value to build a new result, otherwise return the error
* @see https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.and_then
* @param {(val: ValueType) => OutType} value - callback to build a new result
* @example
* Ok<number>(2).andThen((val) => Ok<number>(val + 1)) // Ok<number>(3)
* Err<number, string>('broken').andThen((val) => Ok<number, string>(val + 1)) // Err<number, string>('broken')
*/
andThen<OutType extends ContainerType>(value: (val: ValueType) => OutType): OutType | FalseType;
}
interface IClone<CloneType> {
/**
* Method to clone an object
* @returns {CloneType} - cloned object instance
* @example
* const x = Some(2);
* const y = x.clone();
*/
cloned(): CloneType;
}
interface IEquals<BaseType> {
/**
* Method to compare two objects
* @param {EqualsType} other - object to compare
* @returns {boolean} - true if equal
* @example
* const x = Some(2);
* const y = Some(2);
* console.log(x.eq(y)); // true
*/
eq<EqualsType extends BaseType>(other: EqualsType): boolean;
}
interface IExpect<SomeType> {
/**
* expect unwraps an option and if not a Some value throws an error with the given message.
* @param msgOrError message or error to throw
* @example
* Some(2).expect('the world is ending') // 2
* None<number>().expect('the world is ending') // throws Error('the world is ending')
*/
expect(msgOrError: string | Error): SomeType;
}
type ResultMatchSolver<OkType, ErrType, OkOutput, ErrOutput> = {

@@ -69,37 +5,3 @@ Ok: (value: OkType) => OkOutput;

};
interface IResultMatch<OkType, ErrType> {
/**
* Match the value or error
* @template OkOutput type of the Ok output
* @template ErrOutput type of the Err output
* @param {ResultMatchSolver<OkType, ErrType, OkOutput, ErrOutput>} solver - solver
* @returns {OkOutput | ErrOutput} output
* @example
* Ok<number>(2).match({
* Ok: (value) => value * 2,
* Err: (err) => 0
* }) // 4
*/
match<OkOutput, ErrOutput>(solver: ResultMatchSolver<OkType, ErrType, OkOutput, ErrOutput>): OkOutput | ErrOutput;
}
type OptionMatchSolver<SomeType, Output> = Map<SomeType, () => Output>;
interface IOptionMatch<SomeType> {
/**
* match executes the given function if the option is a Some value, otherwise returns the default value.
* @template Output type of the result
* @param solver map of functions to execute
* @param defaultValue optional default value
* @returns {Output | undefined} the result of the executed function or the default value
* @example
* const output: string = Some(1).match(
* new Map([
* [1, () => 'one'],
* [2, () => 'two'],
* ]),
* 'other',
* );
*/
match<Output>(solver: OptionMatchSolver<SomeType, Output>, defaultValue: Output): Output;
match<Output>(solver: OptionMatchSolver<SomeType, Output>): Output | undefined;
}

@@ -144,32 +46,23 @@ /**

/**
* Interface for the Or method
* Primitive classes provide a valueOf method that returns a value from an object.
* @template ValueType return type of the valueOf method
*/
interface IOr<BaseType, OutType extends BaseType> {
/**
* or method , return either the self true value or the argument true value, otherwise if both are false values return the arguments false value
*
* @see https://doc.rust-lang.org/std/result/enum.Result.html#method.or
* @param {Result} value - compare value
* @returns {Result} - Result based on the self value and the value parameter
* @example
* Err<number>(new Error('broken')).or(Ok<number>(3)) // Ok<number>(3)
* Ok<number>(2).or(Err<number>(new Error('broken'))) // Ok<number>(2)
* Ok<number>(2).or(Ok<number>(3)) // Ok<number>(2)
*/
or<CompareType extends BaseType>(value: CompareType): OutType | CompareType;
interface ValueOf<ValueType> {
valueOf(): ValueType;
}
interface IOrElse<BaseType, ValueType extends BaseType, ErrType = void> {
/**
* orElse method, return either the self when true value or run the callback function and return its result
* @param callbackFunc
* @example
* Ok<number, number>(2).orElse((errValue) => Ok(errValue * 2)) // Ok<number, number>(2)
* Err<number, number>(2).orElse((errValue) => Ok(errValue * 2)) // Ok<number, number>(4)
* Some<number>(2).orElse(() => Some(100)) // Some(2)
* None<number>().orElse(() => Some(100)) // Some(100)
*/
orElse<ElseType extends BaseType>(callbackFunc: (value: ErrType) => ElseType): ValueType | ElseType;
}
/**
* Class constructor with a valueOf method that returns a value from an object.
* @template ValueType return type of the valueOf method
* @example
* Number class => new Number().valueOf() // 0
* String class => new String().valueOf() // ''
*/
type ConstructorWithValueOf<ValueType> = new (...args: never[]) => ValueOf<ValueType>;
interface OptionImplementation<SomeType> extends IUnWrap<SomeType, Error>, IEquals<IOption>, IClone<IOption<SomeType>>, IOr<IOption, IOption<SomeType>>, IOrElse<IOption, IOption<SomeType>>, IAnd<IOption, IOption<SomeType>>, IAndThen<SomeType, IOption, INone<SomeType>>, IExpect<SomeType>, IOptionMatch<SomeType>, IToResult<SomeType> {
type MappedType<IsTrue extends boolean, TrueType, FalseType> = {
true: TrueType;
false: FalseType;
}[`${IsTrue}`];
declare function asMapped<IsTrue extends boolean, TrueType, FalseType>(isTrue: IsTrue, trueValue: TrueType, falseValue: FalseType): MappedType<IsTrue, TrueType, FalseType>;
interface IOptionImplementation<IsTrue extends boolean, SomeType> {
/**

@@ -181,3 +74,3 @@ * Returns true if the option is a Some value.

*/
isSome: boolean;
isSome: MappedType<IsTrue, true, false>;
/**

@@ -189,4 +82,19 @@ * Returns true if the option is a None value.

*/
isNone: boolean;
isNone: MappedType<IsTrue, false, true>;
/**
* Inserts value into Option.
* @param value new value
* @returns {SomeType} currently set value
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.insert
*/
insert(value: SomeType): SomeType;
/**
* Method to clone an Option
* @returns {SomeType} - cloned Option instance
* @example
* const x = Some(2);
* const y = x.clone();
*/
cloned(): IOptionImplementation<IsTrue, SomeType>;
/**
* Returns the contained Some value, consuming the self value.

@@ -203,3 +111,3 @@ *

*/
take(): IOption<SomeType>;
take(): IOptionImplementation<IsTrue, SomeType | undefined>;
/**

@@ -214,65 +122,190 @@ * Replace the actual value with the given one and returns the old Option.

*/
replace(value: SomeType): IOption<SomeType>;
replace(value: SomeType): IOptionImplementation<IsTrue, SomeType>;
/**
* Inserts value into Option.
* @param value new value
* @returns {SomeType} currently set value
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.insert
* Method to unwrap the value or throw an error if None
* @param {Error | ((err: ErrorType) => Error)} err - optional error or function to transform the error
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap
* @example
* Some(2).unwrap() // 2
* None<number>().unwrap() // throws Error
*/
insert(value: SomeType): SomeType;
unwrap(err?: Error | ((err: Error) => Error)): MappedType<IsTrue, SomeType, never>;
/**
* Inserts value into Option if the option is None, then current set value is returned.
* @param value new value
* @returns {SomeType} currently set value
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.get_or_insert
* Method to unwrap the value or if None then return the default value.
* @param defaultValue - default value to return
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap_or
* @example
* Some(2).unwrapOr(3) // 2
* None<number>().unwrapOr(3) // 3
*/
getOrInsert(value: SomeType): SomeType;
unwrapOr<DefType>(defaultValue: DefType): MappedType<IsTrue, SomeType, DefType>;
/**
* Convert Option to string
* Method to unwrap the value or if None then return the default value from function.
* @param {() => DefaultType} fn - function to return default value
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap_or_else
* @example
* Some(2).unwrapOrElse(() => 3) // 2
* None<number>().unwrapOrElse(() => 3) // 3
*/
toString(): `Some(${string})` | `None()`;
unwrapOrElse<DefType>(fn: () => DefType): MappedType<IsTrue, SomeType, DefType>;
/**
* Convert Option to JSON
* @returns {IJsonOption<SomeType>} JSON representation
* Method to unwrap the value or if None then return the default value from constructors valueOf (mimic Rust unwrap_or_default).
* @param BaseConstructor - constructor to return default value from valueOf
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap_or_default
* @example
* Some(2).unwrapOrValueOf(Number) // 2
* None<number>().unwrapOrValueOf(Number) // 0
*/
toJSON(): IJsonOption<SomeType>;
}
interface ISome<SomeType> extends Omit<OptionImplementation<SomeType>, 'isNone' | 'isSome' | 'toJSON'> {
unwrapOrValueOf<DefType>(BaseConstructor: ConstructorWithValueOf<DefType>): MappedType<IsTrue, SomeType, DefType>;
/**
* Returns true if the option is a None value.
* Compare two Options
*/
eq(other: IOption): boolean;
/**
* Method to compare two Options with or operation
* @param value - other Option to compare
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.or
* @example
* Some(2).isNone // false
* Some(2).or(Some(3)) // Some(2)
* None().or(Some(3)) // Some(3)
*/
isNone: false;
or<ValueType>(value: IOption<ValueType>): MappedType<IsTrue, this, IOption<ValueType>>;
/**
* Returns true if the option is a Some value.
* Method to compare two Options with or operation
* @param callbackFunc - function to return default value
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.or_else
* @example
* Some(2).isSome // true
* Some(2).orElse(() => Some(3)) // Some(2)
* None().orElse(() => Some(3)) // Some(3)
*/
isSome: true;
orElse<ValueType>(callbackFunc: (value: SomeType) => IOption<ValueType>): MappedType<IsTrue, this, IOption<ValueType>>;
/**
* Convert Option to JSON
* @returns {IJsonOption<SomeType>} JSON representation
* Method to compare two Options with and operation
* @param value - other Option to compare
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.and
* @example
* Some(2).and(Some(3)) // Some(3)
* None().and(Some(3)) // None()
* Some(2).and(None()) // None()
* None().and(None()) // None()
*/
toJSON(): IJsonSome<SomeType>;
}
interface INone<SomeType> extends Omit<OptionImplementation<SomeType>, 'isNone' | 'isSome' | 'toJSON'> {
and<CompareType>(value: IOption<CompareType>): MappedType<IsTrue, IOption<CompareType>, this>;
/**
* Returns true if the option is a None value.
* Method to compare two Options with andThen operation
* @param callbackFunc - function to return default value
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.and_then
* @example
* None<number>().isNone // true
* Some(2).andThen((val) => Some(val + 1)) // Some(3)
* None().andThen<number>((val) => Some(val + 1)) // None()
*/
isNone: true;
andThen<CompareType, OverrideType = unknown>(callbackFunc: (value: MappedType<IsTrue, SomeType, OverrideType>) => IOption<CompareType>): MappedType<IsTrue, IOption<CompareType>, this>;
/**
* Returns true if the option is a Some value.
* Method to get the value or insert a new value
* @param value - value to insert if None
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.get_or_insert
* @example
* None<number>().isSome // false
* Some(2).getOrInsert(3) // 2
* None().getOrInsert(3) // 3
*/
isSome: false;
getOrInsert(value: SomeType): SomeType;
/**
* Match the Option value with a solver
* @param solver - solver to match the value (Map key to match, callback as resolver)
* @param defaultValue - default value if no match
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.match
* @example
* Some(1).match(
* new Map([
* [1, () => 'one'],
* [2, () => 'two'],
* ]),
* 'other', // default value
* ); // 'one'
* None().match(
* new Map([
* [1, () => 'one'],
* [2, () => 'two'],
* ]),
* 'other', // default value
* ); // 'other'
*/
match<Output>(solver: OptionMatchSolver<SomeType, Output>, defaultValue?: Output): Output | undefined;
match<Output>(solver: OptionMatchSolver<SomeType, Output>, defaultValue: Output): Output;
/**
* expect the Option to be Some or throw an error
* @param error
* @example
* Some(2).expect('error message') // 2
* None().expect('error message') // throws new Error('error message')
*/
expect(error: string | Error): MappedType<IsTrue, SomeType, never>;
/**
* Convert Option to Result and discard the error type
* @returns {IOk<SomeType> | INone<never>} Result
* @example
* Some(2).toResult() // Ok<number>(2)
* None().toResult() // Err<never>()
*/
toResult<ErrType>(err: ErrType): MappedType<IsTrue, IOk<SomeType>, IErr<ErrType>>;
/**
* Convert Option to JSON
* @returns {IJsonOption<SomeType>} JSON representation
* @returns {IJsonSome<SomeType> | IJsonNone} JSON
* @example
* Some(2).toJSON() // {$class: 'Option::Some', value: 2}
* None().toJSON() // {$class: 'Option::None'}
*/
toJSON(): IJsonNone;
toJSON(): MappedType<IsTrue, IJsonSome<SomeType>, IJsonNone>;
/**
* Convert Option to string
* @returns {string} string representation of the Option
* @example
* Some(2).toOptionString() // 'Some(2)'
* None().toOptionString() // 'None()'
*/
toOptionString(): MappedType<IsTrue, `Some(${string})`, 'None()'>;
/**
* Convert Option to string
* @returns {string} string representation of the Option
* @example
* Some(2).toString() // '2'
* None().toString() // 'None'
*/
toString(): string;
}
declare class OptionBuilder<IsSome extends boolean, SomeType = unknown> implements IOptionImplementation<IsSome, SomeType> {
private _isSome;
private value;
constructor(isSome: IsSome, value: SomeType);
get isSome(): MappedType<IsSome, true, false>;
get isNone(): MappedType<IsSome, false, true>;
cloned(): OptionBuilder<IsSome, SomeType>;
insert(value: SomeType): SomeType;
take(): OptionBuilder<IsSome, SomeType | undefined>;
replace(value: SomeType): OptionBuilder<IsSome, SomeType>;
unwrap(err?: Error | ((err: Error) => Error)): MappedType<IsSome, SomeType, never>;
unwrapOr<DefType>(def: DefType): MappedType<IsSome, SomeType, DefType>;
unwrapOrElse<DefType>(fn: () => DefType): MappedType<IsSome, SomeType, DefType>;
unwrapOrValueOf<DefType>(BaseConstructor: ConstructorWithValueOf<DefType>): MappedType<IsSome, SomeType, DefType>;
eq(other: IOption): boolean;
or<ValueType>(value: IOption<ValueType>): MappedType<IsSome, this, IOption<ValueType>>;
orElse<ValueType>(callbackFunc: (value: SomeType) => IOption<ValueType>): MappedType<IsSome, this, IOption<ValueType>>;
and<CompareType>(value: IOption<CompareType>): MappedType<IsSome, IOption<CompareType>, this>;
andThen<CompareType, OverrideType = unknown>(callbackFunc: (value: MappedType<IsSome, SomeType, OverrideType>) => IOption<CompareType>): MappedType<IsSome, IOption<CompareType>, this>;
getOrInsert(value: SomeType): SomeType;
match<Output>(solver: OptionMatchSolver<SomeType, Output>, defaultValue?: Output): Output | undefined;
match<Output>(solver: OptionMatchSolver<SomeType, Output>, defaultValue: Output): Output;
expect(error: string | Error): MappedType<IsSome, SomeType, never>;
toResult<ErrType>(err: ErrType): MappedType<IsSome, IOk<SomeType>, IErr<ErrType>>;
toJSON(): MappedType<IsSome, IJsonSome<SomeType>, IJsonNone>;
toOptionString(): MappedType<IsSome, `Some(${string})`, 'None()'>;
toString(): string;
/**
* Change the value to None
*/
private removeValue;
private setValue;
}
type ISome<SomeType> = OptionBuilder<true, SomeType>;
type INone<SomeType = unknown> = OptionBuilder<false, SomeType>;
/**

@@ -295,46 +328,9 @@ * IOption represents an optional value: every Option is either Some and contains a value and type, or None which does not any type.

*/
type IOption<SomeType = unknown> = ISome<SomeType> | INone<SomeType>;
type IOption<SomeType = unknown> = OptionBuilder<true, SomeType> | OptionBuilder<false, SomeType>;
declare function isOption<SomeType>(value: unknown): value is IOption<SomeType>;
declare function isSome<SomeType>(value: unknown): value is ISome<SomeType>;
declare function isNone<SomeType = unknown>(value: unknown): value is INone<SomeType>;
declare function None<SomeType>(noneInstance?: IJsonNone | INone<SomeType>): INone<SomeType>;
declare function None<SomeType = unknown>(noneInstance?: IJsonNone | INone): OptionBuilder<false, SomeType>;
declare class OptionBuilder<SomeType> implements OptionImplementation<SomeType> {
private _isSome;
private value;
constructor(isSome: false, value?: IJsonNone);
constructor(isSome: true, value: SomeType | IJsonSome<SomeType>);
get isNone(): boolean;
get isSome(): boolean;
expect(msgOrError: string | Error): SomeType;
unwrap(err?: Error | ((err: Error) => Error) | undefined): SomeType;
unwrapOr<DefType>(def: DefType): DefType | SomeType;
unwrapOrElse<DefType>(fn: () => DefType): DefType | SomeType;
unwrapOrValueOf(BaseConstructor: ConstructorWithValueOf<SomeType>): SomeType;
take(): IOption<SomeType>;
cloned(): IOption<SomeType>;
eq<OtherType extends IOption>(other: OtherType): boolean;
or<CompareType extends IOption>(value: CompareType): IOption<SomeType> | CompareType;
orElse<ElseResult extends IOption>(callbackFunc: (value: void) => ElseResult): IOption<SomeType> | ElseResult;
and<CompareType extends IOption>(value: CompareType): IOption<SomeType> | CompareType;
andThen<OutType extends IOption>(callbackFunc: (val: SomeType) => OutType): OutType | INone<SomeType>;
replace(value: SomeType): IOption<SomeType>;
insert(value: SomeType): SomeType;
getOrInsert(value: SomeType): SomeType;
match<Output>(solver: OptionMatchSolver<SomeType, Output>, defaultValue?: Output | undefined): Output | undefined;
match<Output>(solver: OptionMatchSolver<SomeType, Output>, defaultValue: Output): Output;
toResult<ErrType>(err: ErrType): IResult<SomeType, ErrType>;
toString(): `Some(${string})` | `None()`;
toJSON(): IJsonOption<SomeType>;
/**
* set the value of the option and change the state to Some
* @param value - the value to set
* @returns the value that was set
*/
private setValue;
private removeValue;
private thisIsSome;
private thisIsNone;
private getName;
}
declare function isOption<SomeType>(value: unknown): value is IOption<SomeType>;
/**

@@ -372,16 +368,19 @@ * Simple function to wrap a possible undefined value as None

*/
declare function Option<SomeType>(instance: ISome<SomeType> | INone<SomeType> | IJsonOption<SomeType>): ISome<SomeType> | INone<SomeType>;
declare function Option<SomeType>(instance: ISome<SomeType> | INone | IJsonOption<SomeType>): ISome<SomeType> | INone;
declare function Some<SomeType = unknown>(value: SomeType | IJsonSome<SomeType> | ISome<SomeType>): ISome<SomeType>;
interface IResultImplementation<OkType, ErrType> extends IUnWrap<OkType, ErrType>, IEquals<IResult>, IOr<IResult, IResult<OkType, ErrType>>, IOrElse<IResult, IResult<OkType, ErrType>, ErrType>, IAnd<IResult, IResult<OkType, ErrType>>, IClone<IResult<OkType, ErrType>>, IAndThen<OkType, IResult, IErr<OkType, ErrType>>, IResultMatch<OkType, ErrType> {
declare const optionNoneClass = "Option::None";
declare const optionSomeClass = "Option::Some";
declare function fromJsonOption<SomeType>(json: IJsonNone): INone<SomeType>;
declare function fromJsonOption<SomeType>(json: IJsonSome<SomeType>): ISome<SomeType>;
declare function fromJsonOption<SomeType>(json: IJsonOption<SomeType>): IOption<SomeType>;
declare function isJsonOption<SomeType>(json: unknown): json is IJsonOption<SomeType>;
declare function isJsonSome<SomeType>(json: unknown): json is IJsonSome<SomeType>;
declare function isJsonNone(json: unknown): json is IJsonNone;
declare function buildJsonSome<SomeType>(value: SomeType): IJsonSome<SomeType>;
declare function buildJsonNone(): IJsonNone;
interface IResultBuild<IsOk = true, OkType = unknown, ErrType = unknown> {
/**
* Try to get value, otherwise return undefined
* @returns {OkType | undefined} value or undefined
* @example
* Ok<number>(2).ok() // 2
* Err<number>(new Error('broken')).ok() // undefined
*/
ok(): OkType | undefined;
/**
* Check that result is not an error

@@ -391,13 +390,13 @@ * @returns {boolean} true if result is not an error

* Ok<number>(2).isOk // true
* Err<number>(new Error('broken')).isOk // false
* Err<Error>(new Error('broken')).isOk // false
*/
isOk: boolean;
isOk: IsOk;
/**
* Try to get the error, otherwise return undefined
* @returns {ErrType | undefined} error or undefined
* Try to get value, otherwise return undefined
* @returns {OkType | undefined} value or undefined
* @example
* Ok<number>(2).err() // undefined
* Err<number>(new Error('broken')).err() // Error('broken')
* Ok<number>(2).ok() // 2
* Err<Error>(new Error('broken')).ok() // undefined
*/
err(): ErrType | undefined;
ok(): IsOk extends true ? OkType : undefined;
/**

@@ -408,97 +407,143 @@ * Check that result is an error

* Ok<number>(2).isErr // false
* Err<number>(new Error('broken')).isErr // true
* Err<Error>(new Error('broken')).isErr // true
*/
isErr: boolean;
isErr: IsOk extends false ? true : false;
/**
* Convert result to option and discard the error type
* Try to get the error, otherwise return undefined
* @returns {ErrType | undefined} error or undefined
* @example
* Ok<number>(2).err() // undefined
* Err<Error>(new Error('broken')).err() // Error('broken')
*/
toOption(): IOption<OkType>;
err(): IsOk extends false ? ErrType : undefined;
/**
* Convert result to string
* Method to unwrap the value or throw an error
* @param {Error | ((err: ErrorType) => Error)} err - optional error or function to transform the error
* @example
* Ok<number>(2).unwrap() // 2
* Err<Error>(new Error('broken')).unwrap() // throws Error('broken')
*/
toString(): `Ok(${string})` | `Err(${string})`;
unwrap(err?: Error | ((err: ErrType) => Error)): IsOk extends true ? OkType : never;
/**
* Convert result to JSON {$class: 'Result::Ok', value: OkType} or {$class: 'Result::Err', value: ErrType}
* @returns {IJsonResult<OkType, ErrType>} JSON representation of the result
* Method to unwrap the value or if error return the default value
* @param defaultValue - default value to return if error
* @example
* Ok<number>(2).unwrapOr(0) // 2
* Err<number>(new Error('broken')).unwrapOr(0) // 0
*/
toJSON(): IJsonResult<OkType, ErrType>;
}
interface IOk<OkType, ErrType> extends Omit<IResultImplementation<OkType, ErrType>, 'isOk' | 'isErr' | 'ok' | 'err' | 'toOption' | 'toJSON'> {
unwrapOr<DefaultType>(defaultValue: DefaultType): IsOk extends true ? OkType : DefaultType;
/**
* Check that result is not an error
* @returns {boolean} true if result is not an error
* Method to unwrap the value or if error return default value from function
* @param {() => DefaultType} callbackFunc - function to return default value
* @example
* Ok<number>(2).isOk // true
* Ok<number>(2).unwrapOrElse(() => 0) // 2
* Err<number>(new Error('broken')).unwrapOrElse(() => 0) // 0
*/
isOk: true;
unwrapOrElse<DefaultType>(callbackFunc: () => DefaultType): IsOk extends true ? OkType : DefaultType;
/**
* Try to get value, otherwise return undefined
* @returns {OkType | undefined} value or undefined
* Method to unwrap the value or if error return default value from constructors valueOf
* @param BaseConstructor - constructor to return default value from valueOf
* @example
* Ok<number>(2).ok() // 2
* Ok<number>(2).unwrapOrValueOf(Number) // 2
* Err<Error>(new Error('broken')).unwrapOrValueOf(Number) // 0 (Number.valueOf())
*/
ok(): OkType;
unwrapOrValueOf<ValueType>(BaseConstructor: ConstructorWithValueOf<ValueType>): IsOk extends true ? OkType : ValueType;
/**
* Check that result is an error
* @returns {boolean} true if result is an error
* Method to compare two results
* @param other - other result to compare
* @returns {boolean} true if results are equal
* @example
* Ok<number>(2).isErr // false
* Ok<number>(2).eq(Ok<number>(2)) // true
* Ok<number>(2).eq(Ok<number>(3)) // false
* Err<number>(2).eq(Err<number>(2)) // true
*/
isErr: false;
eq(other: IResult): boolean;
/**
* Try to get the error, otherwise return undefined
* @returns {ErrType | undefined} error or undefined
* Method to combine two results, if the first result is true return the second result, otherwise return the first result
* @param value - compare value
* @returns {Result} - Result based on the self value and the value parameter
* @example
* Ok<number>(2).err() // undefined
* Err<Error>(new Error('broken')).and(Ok<number>(3)) // Err<Error>(new Error('broken'))
* Ok<number>(2).and(Err<number>(new Error('broken'))) // Err<Error>(new Error('broken'))
* Ok<number>(2).and(Ok<number>(3)) // Ok<number>(3)
*/
err(): undefined;
and<CompareType>(value: IResult<CompareType>): IsOk extends true ? IResult<CompareType> : this;
/**
* Convert result to option and discard the error type
* Method to combine two results, if the first result is true use the value to build a new result, otherwise return the error
* @param callbackFunc - callback to build a new result
* @returns {Result} - Result based on the self value and the value parameter
* @example
* Ok<number>(2).andThen((val) => Ok<number>(val + 1)) // Ok<number>(3)
* Err<'broken'>('broken').andThen<number>((val) => Ok<number>(val + 1)) // Err<'broken'>('broken')
*/
toOption(): ISome<OkType>;
andThen<OutType, Override = unknown>(callbackFunc: (val: IsOk extends true ? OkType : Override) => IResult<OutType>): IsOk extends true ? IResult<OutType> : this;
/**
* Convert result to JSON {$class: 'Result::Ok', value: OkType} or {$class: 'Result::Err', value: ErrType}
* @returns {IJsonResult<OkType, ErrType>} JSON representation of the result
* Method to combine two results, if the first result is false return the second result, otherwise return the first result
* @param value - compare value
* @returns {Result} - Result based on the self value and the value parameter
* @example
* Err<Error>(new Error('broken')).or(Ok<number>(3)) // Ok<number>(3)
* Ok<number>(2).or(Err<Error>(new Error('broken'))) // Ok<number>(2)
* Ok<number>(2).or(Ok<number>(3)) // Ok<number>(2)
*/
toJSON(): IJsonOk<OkType>;
}
interface IErr<OkType, ErrType> extends Omit<IResultImplementation<OkType, ErrType>, 'isOk' | 'isErr' | 'ok' | 'err' | 'toJSON'> {
or<CompareType>(value: IResult<CompareType>): IsOk extends true ? this : IResult<CompareType>;
/**
* Check that result is not an error
* @returns {boolean} true if result is not an error
* Method to combine two results, if the first result is false use the error to build a new result, otherwise return the first result
* @param callbackFunc - callback to build a new result
* @returns {Result} - Result based on the self value and the value parameter
* @example
* Err<number>(new Error('broken')).isOk // false
* Ok<number>(2).orElse<number, number>((errValue) => Ok(errValue * 2)) // Ok<number>(2)
* Err<number>(2).orElse<number>((errValue) => Ok(errValue * 2)) // Ok<number>(4)
*/
isOk: false;
orElse<CompareType, Override = unknown>(callbackFunc: (value: IsOk extends true ? Override : ErrType) => IResult<CompareType>): IsOk extends true ? this : IResult<CompareType>;
/**
* Try to get value, otherwise return undefined
* @returns {OkType | undefined} value or undefined
* Method to clone an result
* @returns {CloneType} - cloned result instance
* @example
* Err<number>(new Error('broken')).ok() // undefined
* const x = Ok(2);
* const y = x.clone(); // Ok(2)
*/
ok(): undefined;
clone(): IResultBuild<IsOk, OkType, ErrType>;
/**
* Check that result is an error
* @returns {boolean} true if result is an error
* Method to match the value or error
* @param solver - solver callback
* @returns {OkOutput | ErrOutput} output
* @example
* Err<number>(new Error('broken')).isErr // true
* Ok<number>(2).match({
* Ok: (value) => value * 2,
* Err: (err) => 0
* }) // 4
* Err<number>(2).match({
* Ok: (value) => value * 2,
* Err: (err) => 0
* }) // 0
*/
isErr: true;
match<OkOutput, ErrOutput>(solver: ResultMatchSolver<OkType, ErrType, OkOutput, ErrOutput>): IsOk extends true ? OkOutput : ErrOutput;
/**
* Try to get the error, otherwise return undefined
* @returns {ErrType | undefined} error or undefined
* Convert result to option and discard the error type
* @returns {ISome<OkType> | INone<never>} option
* @example
* Err<number>(new Error('broken')).err() // Error('broken')
* Ok<number>(2).toOption() // Some<number>(2)
* Err<number>(2).toOption() // None<never>()
*/
err(): ErrType;
toOption(): IsOk extends true ? ISome<OkType> : INone<never>;
/**
* Convert result to option and discard the error type
* Convert result to string
* @returns {string} string representation of the result
* @example
* Ok<number>(2).toString() // 'Ok(2)'
* Err<number>(2).toString() // 'Err(2)'
*/
toOption(): INone<OkType>;
toString(): IsOk extends true ? `Ok(${string})` : `Err(${string})`;
/**
* Convert result to JSON {$class: 'Result::Ok', value: OkType} or {$class: 'Result::Err', value: ErrType}
* @returns {IJsonResult<OkType, ErrType>} JSON representation of the result
* @returns {IJsonOk<OkType> | IJsonErr<ErrType>} JSON representation of the result
* @example
* Ok<number>(2).toJSON() // {$class: 'Result::Ok', value: 2}
* Err<number>(2).toJSON() // {$class: 'Result::Err', value: 2}
*/
toJSON(): IJsonErr<ErrType>;
toJSON(): IsOk extends true ? IJsonOk<OkType> : IJsonErr<ErrType>;
}
type IErr<ErrType = unknown, OkType = never> = IResultBuild<false, OkType, ErrType>;
type IOk<OkType = unknown, ErrType = never> = IResultBuild<true, OkType, ErrType>;
/**

@@ -509,8 +554,7 @@ * Result type, this type contains types for both Ok and Err

* @example
* async function action(): Promise<Result<number>> {
* try {
* return Ok<number>(await getNumber());
* } catch (e) {
* return Err<number>(e);
* }
* async function action(): Promise<IResult<number>> {
* try {
* return Ok(await getNumber());
* } catch (e: unknown) {
* return Err(e);
* }

@@ -524,3 +568,3 @@ * const result = await action();

*/
type IResult<OkType = unknown, ErrType = unknown> = IOk<OkType, ErrType> | IErr<OkType, ErrType>;
type IResult<OkType = unknown, ErrType = unknown> = IResultBuild<true, OkType, ErrType> | IResultBuild<false, OkType, ErrType>;
/**

@@ -533,59 +577,6 @@ * Utility type for OkType or Result

interface IToResult<ValueType> {
/**
* Method to convert as Result
* @param err Result Error type if conversion fails.
* @returns {IResult<SomeType, ErrType>} Result
*/
toResult<ErrType>(err: ErrType): IResult<ValueType, ErrType>;
}
/**
* Primitive classes provide a valueOf method that returns a value from an object.
* @template ValueType return type of the valueOf method
*/
interface ValueOf<ValueType> {
valueOf(): ValueType;
}
/**
* Class constructor with a valueOf method that returns a value from an object.
* @template ValueType return type of the valueOf method
* @example
* Number class => new Number().valueOf() // 0
* String class => new String().valueOf() // ''
*/
type ConstructorWithValueOf<ValueType> = new (...args: never[]) => ValueOf<ValueType>;
interface IUnWrap<ValueType, ErrorType> {
/**
* Method to unwrap the value or throw an error
* @param {Error | ((err: ErrorType) => Error)} err - optional error or function to transform the error
* @example
* Ok<number>(2).unwrap() // 2
* Err<number>(new Error('broken')).unwrap() // throws Error('broken')
* Some(2).unwrap() // 2
* None<number>().unwrap() // throws Error
*/
unwrap(err?: Error | ((err: ErrorType) => Error)): ValueType;
/**
* Method to unwrap the value or if error return the default value
* @param defaultValue - default value to return
*/
unwrapOr<DefaultType>(defaultValue: DefaultType): DefaultType | ValueType;
/**
* Method to unwrap the value or if error return default value from function
* @param {() => DefaultType} callbackFunc - function to return default value
*/
unwrapOrElse<DefaultType>(callbackFunc: () => DefaultType): DefaultType | ValueType;
/**
* Method to unwrap the value or if error return default value from constructors valueOf
* @param constructorValueOf - constructor to return default value from valueOf
*/
unwrapOrValueOf(constructorValueOf: ConstructorWithValueOf<ValueType>): ValueType;
}
/**
* Build Err result or return if already a Result
* @template OkType ok type
* @template ErrType error type
* @template OkType ok type, optional default unknown
* @param error - error to wrap or return if already a Result

@@ -597,24 +588,28 @@ * @returns {IResult<OkType, ErrType>} - Result

*/
declare function Err<OkType = unknown, ErrType = unknown>(error: ErrType | IErr<OkType, ErrType> | IJsonErr<ErrType>): IErr<OkType, ErrType>;
declare function Err<OkType = unknown, ErrType = unknown>(error: ErrType | IResult<OkType, ErrType> | IJsonErr<ErrType>): IResult<OkType, ErrType>;
declare function Err<ErrType, _OkType = unknown>(error: ErrType | IErr<ErrType> | IJsonErr<ErrType>): IErr<ErrType>;
declare function Err<ErrType, OkType = unknown>(error: ErrType | IResult<OkType, ErrType> | IJsonErr<ErrType>): IResult<OkType, ErrType>;
declare class ErrInstance<OkType, ErrType> implements IErr<OkType, ErrType> {
/**
* Err Result instance
* @template ErrType error type
*/
declare class ErrInstance<ErrType> implements IErr<ErrType> {
private readonly error;
readonly isOk = false;
readonly isErr = true;
constructor(error: ErrType | IJsonErr<ErrType>);
get isOk(): false;
ok(): undefined;
get isErr(): true;
err(): ErrType;
toOption(): INone<OkType>;
unwrap(err?: Error | ((err: ErrType) => Error) | undefined): OkType;
toOption(): INone<never>;
unwrap(err?: Error | ((err: ErrType) => Error)): never;
unwrapOr<DefaultType>(defaultValue: DefaultType): DefaultType;
unwrapOrElse<DefaultType>(callbackFunc: () => DefaultType): DefaultType;
unwrapOrValueOf(BaseConstructor: ConstructorWithValueOf<OkType>): OkType;
eq<EqualsType extends IResult>(other: EqualsType): boolean;
or<CompareType extends IResult>(value: CompareType): CompareType;
orElse<ElseType extends IResult>(callbackFunc: (value: ErrType) => ElseType): ElseType;
and<CompareType extends IResult>(_value: CompareType): IResult<OkType, ErrType>;
cloned(): IResult<OkType, ErrType>;
andThen<OutType extends IResult>(_value: (val: OkType) => OutType): IErr<OkType, ErrType>;
match<OkOutput, ErrOutput>(solver: ResultMatchSolver<OkType, ErrType, OkOutput, ErrOutput>): ErrOutput;
unwrapOrValueOf<ValueType>(BaseConstructor: ConstructorWithValueOf<ValueType>): ValueType;
eq(other: IResult): boolean;
or<CompareResult extends IResult>(value: CompareResult): CompareResult;
orElse<CompareResult extends IResult>(callbackFunc: (value: ErrType) => CompareResult): CompareResult;
and<CompareResult extends IResult>(_value: CompareResult): this;
clone(): ErrInstance<ErrType>;
andThen<OutType>(_callbackFunc: (val: never) => IResult<OutType>): this;
match<OkOutput, ErrOutput>(solver: ResultMatchSolver<unknown, ErrType, OkOutput, ErrOutput>): ErrOutput;
toString(): `Err(${string})`;

@@ -629,4 +624,4 @@ toJSON(): IJsonErr<ErrType>;

declare function isJsonErr<OkType, ErrType>(json: unknown): json is IJsonErr<ErrType>;
declare function fromJsonResult<OkType, ErrType>(json: IJsonErr<ErrType>): IErr<OkType, ErrType>;
declare function fromJsonResult<OkType, ErrType>(json: IJsonOk<OkType>): IOk<OkType, ErrType>;
declare function fromJsonResult<_OkType, ErrType>(json: IJsonErr<ErrType>): IErr<ErrType>;
declare function fromJsonResult<OkType, _ErrType>(json: IJsonOk<OkType>): IOk<OkType>;
declare function fromJsonResult<OkType, ErrType>(json: IJsonResult<OkType, ErrType>): IResult<OkType, ErrType>;

@@ -637,3 +632,3 @@

* @template OkType ok type
* @template ErrType error type
* @template ErrType error type, optional default unknown
* @param value - value to wrap or return if already a Result

@@ -644,24 +639,28 @@ * @returns {IResult<OkType, ErrType>} - Result

*/
declare function Ok<OkType = unknown, ErrType = unknown>(value: OkType | IOk<OkType, ErrType> | IJsonOk<OkType>): IOk<OkType, ErrType>;
declare function Ok<OkType = unknown, ErrType = unknown>(value: OkType | IResult<OkType, ErrType> | IJsonOk<OkType>): IResult<OkType, ErrType>;
declare function Ok<OkType, _ErrType = unknown>(value: OkType | IOk<OkType> | IJsonOk<OkType>): IOk<OkType>;
declare function Ok<OkType, ErrType = unknown>(value: OkType | IResult<OkType, ErrType> | IJsonOk<OkType>): IResult<OkType, ErrType>;
declare class OkInstance<OkType, ErrType> implements IOk<OkType, ErrType> {
/**
* Ok Result instance
* @template OkType - Ok type
*/
declare class OkInstance<OkType> implements IOk<OkType> {
private readonly value;
readonly isOk = true;
readonly isErr = false;
constructor(value: OkType | IJsonOk<OkType>);
get isOk(): true;
ok(): OkType;
get isErr(): false;
err(): undefined;
match<OkOutput, ErrOutput>(solver: ResultMatchSolver<OkType, ErrType, OkOutput, ErrOutput>): OkOutput;
match<OkOutput, ErrOutput>(solver: ResultMatchSolver<OkType, unknown, OkOutput, ErrOutput>): OkOutput;
toOption(): ISome<OkType>;
unwrap(_err?: ((err: ErrType) => Error) | undefined): OkType;
unwrap(_err?: Error | ((err: never) => Error)): OkType;
unwrapOr<DefaultType>(_defaultValue: DefaultType): OkType;
unwrapOrElse<DefaultType>(_callbackFunc: () => DefaultType): OkType;
unwrapOrValueOf(_constructorValueOf: ConstructorWithValueOf<OkType>): OkType;
eq<EqualsType extends IResult>(other: EqualsType): boolean;
or<CompareType extends IResult>(_value: CompareType): IResult<OkType, ErrType>;
orElse<ElseType extends IResult>(_callbackFunc: (value: ErrType) => ElseType): IResult<OkType, ErrType>;
and<CompareType extends IResult>(value: CompareType): CompareType;
cloned(): IResult<OkType, ErrType>;
andThen<OutType extends IResult>(value: (val: OkType) => OutType): OutType;
unwrapOrValueOf<ValueType>(_constructorValueOf: ConstructorWithValueOf<ValueType>): OkType;
eq(other: IResult): boolean;
or<CompareType>(_value: IResult<CompareType>): this;
orElse<CompareType, Override>(_callbackFunc: (value: Override) => IResult<CompareType>): this;
and<CompareType>(value: IResult<CompareType>): IResult<CompareType>;
clone(): OkInstance<OkType>;
andThen<OutType>(callbackFunc: (val: OkType) => IResult<OutType>): IResult<OutType>;
toString(): `Ok(${string})`;

@@ -727,3 +726,3 @@ toJSON(): IJsonOk<OkType>;

*/
declare function safeResultBuilder<TArgs extends any[], OkType = unknown, ErrType = unknown>(func: (...args: TArgs) => IResultOrOkType<OkType, ErrType>): (...args: TArgs) => IResult<OkType, ErrType>;
declare function safeResultBuilder<TArgs extends any[], OkType, ErrType>(func: (...args: TArgs) => IResultOrOkType<OkType, ErrType>): (...args: TArgs) => IResult<OkType, ErrType>;
/**

@@ -743,2 +742,2 @@ * safe wrapper for function

export { type ConstructorWithValueOf, Err, ErrInstance, type IAnd, type IAndThen, type IClone, type IEquals, type IErr, type IExpect, type IJsonErr, type IJsonNone, type IJsonOk, type IJsonOption, type IJsonResult, type IJsonSome, type INone, type IOk, type IOption, type IOptionMatch, type IOr, type IOrElse, type IResult, type IResultImplementation, type IResultMatch, type IResultOrOkType, type ISome, type IToResult, type IUnWrap, None, Ok, OkInstance, Option, OptionBuilder, type OptionImplementation, type OptionMatchSolver, type ResultMatchSolver, Some, type ValueOf, fromJsonResult, isJsonErr, isJsonOk, isJsonResult, isOption, isResult, nanOption, nullishOptionWrap, safeAsyncResult, safeAsyncResultBuilder, safeResult, safeResultBuilder, undefinedOptionWrap };
export { type ConstructorWithValueOf, Err, ErrInstance, type IErr, type IJsonErr, type IJsonNone, type IJsonOk, type IJsonOption, type IJsonResult, type IJsonSome, type INone, type IOk, type IOption, type IOptionImplementation, type IResult, type IResultBuild, type IResultOrOkType, type ISome, type MappedType, None, Ok, OkInstance, Option, OptionBuilder, type OptionMatchSolver, type ResultMatchSolver, Some, type ValueOf, asMapped, buildJsonNone, buildJsonSome, fromJsonOption, fromJsonResult, isJsonErr, isJsonNone, isJsonOk, isJsonOption, isJsonResult, isJsonSome, isNone, isOption, isResult, isSome, nanOption, nullishOptionWrap, optionNoneClass, optionSomeClass, safeAsyncResult, safeAsyncResultBuilder, safeResult, safeResultBuilder, undefinedOptionWrap };

@@ -1,479 +0,2 @@

// src/option/Some.ts
function Some(value) {
if (isOption(value)) {
return value;
}
return new OptionBuilder(true, value);
}
// src/option/JsonOption.ts
function fromJsonOption(json) {
if (json.$class === "Option::None") {
return None();
} else {
return Some(json.value);
}
}
function isJsonOption(json) {
return typeof json === "object" && json !== null && "$class" in json && (json.$class === "Option::None" || json.$class === "Option::Some");
}
function getJsonOptionValue(option) {
if (option.$class === "Option::Some") {
return option.value;
}
return void 0;
}
// src/option/OptionBuilder.ts
var OptionBuilder = class _OptionBuilder {
constructor(isSome, value) {
this._isSome = isSome;
this.value = isJsonOption(value) ? getJsonOptionValue(value) : value;
}
get isNone() {
return !this._isSome;
}
get isSome() {
return this._isSome;
}
expect(msgOrError) {
if (this.thisIsSome()) {
return this.value;
}
throw typeof msgOrError === "string" ? new Error(msgOrError) : msgOrError;
}
unwrap(err) {
if (this.thisIsSome()) {
return this.value;
}
const error = new Error(`${this.getName()}: No value was set`);
if (err) {
if (typeof err === "function") {
throw err(error);
}
throw err;
}
throw error;
}
unwrapOr(def) {
if (this.thisIsSome()) {
return this.value;
}
return def;
}
unwrapOrElse(fn) {
if (this.thisIsSome()) {
return this.value;
}
return fn();
}
unwrapOrValueOf(BaseConstructor) {
if (this.thisIsSome()) {
return this.value;
}
return new BaseConstructor().valueOf();
}
take() {
const result = this.cloned();
this.removeValue();
return result;
}
cloned() {
if (this.thisIsSome()) {
return new _OptionBuilder(true, this.value);
}
return new _OptionBuilder(false);
}
eq(other) {
if (this._isSome !== other.isSome) {
return false;
}
if (this._isSome) {
return this.value === other.unwrap();
}
return true;
}
or(value) {
if (this.thisIsSome()) {
return this;
}
return value;
}
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
orElse(callbackFunc) {
if (this.thisIsSome()) {
return this;
}
return callbackFunc();
}
and(value) {
if (this.thisIsNone()) {
return this;
}
return value;
}
andThen(callbackFunc) {
if (this.thisIsSome()) {
return callbackFunc(this.value);
}
return this;
}
replace(value) {
const old = this.cloned();
this.setValue(value);
return old;
}
insert(value) {
return this.setValue(value);
}
getOrInsert(value) {
if (!this.thisIsSome()) {
return this.setValue(value);
}
return this.value;
}
match(solver, defaultValue) {
for (const [key, value] of solver.entries()) {
if (this._isSome && this.value === key) {
return value();
}
}
return defaultValue;
}
toResult(err) {
if (this.thisIsSome()) {
return Ok(this.value);
}
return Err(err);
}
toString() {
if (this.thisIsSome()) {
return `${this.getName()}(${String(this.value)})`;
}
return `${this.getName()}()`;
}
toJSON() {
if (this.thisIsSome()) {
return {
$class: "Option::Some",
value: this.value
};
} else {
return {
$class: "Option::None"
};
}
}
/**
* set the value of the option and change the state to Some
* @param value - the value to set
* @returns the value that was set
*/
setValue(value) {
this._isSome = true;
this.value = value;
return value;
}
removeValue() {
const value = this.value;
this._isSome = false;
this.value = void 0;
return value;
}
thisIsSome() {
return this._isSome;
}
thisIsNone() {
return !this._isSome;
}
getName() {
return this.thisIsSome() ? "Some" : "None";
}
};
function isOption(value) {
return value instanceof OptionBuilder;
}
// src/option/None.ts
function None(noneInstance) {
if (isOption(noneInstance)) {
return noneInstance;
}
return new OptionBuilder(false, noneInstance);
}
// src/option/optionUtils.ts
function undefinedOptionWrap(value) {
if (value === void 0) {
return None();
}
return Some(value);
}
function nullishOptionWrap(value) {
if (value === void 0 || value === null) {
return None();
}
if (typeof value === "number" && isNaN(value)) {
return None();
}
return Some(value);
}
function nanOption(value) {
if (isNaN(value)) {
return None();
}
return Some(value);
}
function Option(instance) {
if (isOption(instance)) {
return instance;
}
if (isJsonOption(instance)) {
return fromJsonOption(instance);
}
throw new Error("Invalid Option instance");
}
// src/result/OkInstance.ts
var OkInstance = class _OkInstance {
constructor(value) {
this.isOk = true;
this.isErr = false;
this.value = isJsonOk(value) ? value.value : value;
}
ok() {
return this.value;
}
err() {
return void 0;
}
match(solver) {
return solver.Ok(this.value);
}
toOption() {
return Some(this.value);
}
unwrap(_err) {
return this.value;
}
unwrapOr(_defaultValue) {
return this.value;
}
unwrapOrElse(_callbackFunc) {
return this.value;
}
unwrapOrValueOf(_constructorValueOf) {
return this.value;
}
eq(other) {
return this.value === other.ok();
}
or(_value) {
return this;
}
orElse(_callbackFunc) {
return this;
}
and(value) {
return value;
}
cloned() {
return new _OkInstance(this.value);
}
andThen(value) {
return value(this.value);
}
toString() {
return `Ok(${String(this.value)})`;
}
toJSON() {
return {
$class: "Result::Ok",
value: this.value
};
}
};
// src/result/ResultInstance.ts
function isResult(value) {
return value instanceof OkInstance || value instanceof ErrInstance;
}
// src/result/Ok.ts
function Ok(value) {
if (isResult(value)) {
return value;
}
return new OkInstance(value);
}
// src/result/JsonResult.ts
function isJsonResult(json) {
return typeof json === "object" && json !== null && "$class" in json && (json.$class === "Result::Ok" || json.$class === "Result::Err");
}
function isJsonOk(json) {
return isJsonResult(json) && json.$class === "Result::Ok";
}
function isJsonErr(json) {
return isJsonResult(json) && json.$class === "Result::Err";
}
function fromJsonResult(json) {
if (json.$class === "Result::Ok") {
return Ok(json.value);
} else {
return Err(json.value);
}
}
// src/result/ErrInstance.ts
var ErrInstance = class _ErrInstance {
constructor(error) {
this.isOk = false;
this.isErr = true;
this.error = isJsonErr(error) ? error.value : error;
}
ok() {
return void 0;
}
err() {
return this.error;
}
toOption() {
return None();
}
unwrap(err) {
if (err) {
if (typeof err === "function") {
throw err(this.error);
}
throw err;
}
throw this.error;
}
unwrapOr(defaultValue) {
return defaultValue;
}
unwrapOrElse(callbackFunc) {
return callbackFunc();
}
unwrapOrValueOf(BaseConstructor) {
return new BaseConstructor().valueOf();
}
eq(other) {
return this.error === other.err();
}
or(value) {
return value;
}
orElse(callbackFunc) {
return callbackFunc(this.error);
}
and(_value) {
return this;
}
cloned() {
return new _ErrInstance(this.error);
}
andThen(_value) {
return this;
}
match(solver) {
return solver.Err(this.error);
}
toString() {
return `Err(${this.getErrorInstanceName()}${this.getErrorInstanceMessage()})`;
}
toJSON() {
return {
$class: "Result::Err",
value: this.error
};
}
getErrorInstanceName() {
if (typeof this.error === "object" && this.error !== null) {
return this.error.constructor.name;
}
return "UnknownErrorInstance";
}
getErrorInstanceMessage() {
if (this.error instanceof Error) {
return `: '${this.error.message}'`;
}
return `: '${JSON.stringify(this.error)}'`;
}
};
// src/result/Err.ts
function Err(error) {
if (isResult(error)) {
return error;
}
return new ErrInstance(error);
}
// src/result/safeAsyncResult.ts
async function promiseSettledAsResult(callPromise) {
const result = (await Promise.allSettled([callPromise]))[0];
if (result.status === "fulfilled") {
return Ok(result.value);
} else {
return Err(result.reason);
}
}
function safeAsyncResultBuilder(func) {
return async (...args) => {
try {
return promiseSettledAsResult(func(...args));
} catch (err) {
return Err(err);
}
};
}
async function safeAsyncResult(func) {
try {
return promiseSettledAsResult(typeof func === "function" ? func() : func);
} catch (err) {
return Err(err);
}
}
// src/result/safeResult.ts
function safeResultBuilder(func) {
return (...args) => {
try {
return Ok(func(...args));
} catch (err) {
return Err(err);
}
};
}
function safeResult(func) {
try {
return Ok(func());
} catch (err) {
return Err(err);
}
}
export {
Err,
ErrInstance,
None,
Ok,
OkInstance,
Option,
OptionBuilder,
Some,
fromJsonResult,
isJsonErr,
isJsonOk,
isJsonResult,
isOption,
isResult,
nanOption,
nullishOptionWrap,
safeAsyncResult,
safeAsyncResultBuilder,
safeResult,
safeResultBuilder,
undefinedOptionWrap
};
function o(e,r,t){return{true:r,false:t}[`${e}`]}function i(e){return I(e)?e:f(e)?new p(!0,e.value):new p(!0,e)}var l="Option::None",O="Option::Some";function S(e){return e.$class===l?u():i(e.value)}function m(e){return typeof e=="object"&&e!==null&&"$class"in e&&(e.$class===l||e.$class===O)}function f(e){return m(e)&&e.$class===O}function c(e){return m(e)&&e.$class===l}function k(e){return{$class:O,value:e}}function E(){return{$class:l}}var p=class e{constructor(r,t){this._isSome=r,this.value=t}get isSome(){return o(this._isSome,!0,!1)}get isNone(){return o(this._isSome,!1,!0)}cloned(){return new e(this._isSome,this.value)}insert(r){return this.setValue(r)}take(){return new e(this._isSome,this.removeValue())}replace(r){let t=this.cloned();return this.setValue(r),t}unwrap(r){if(!this._isSome){let t=new Error("None: No value was set");throw r?typeof r=="function"?r(t):r:t}return{true:this.value,false:void 0}[`${this._isSome}`]}unwrapOr(r){return{true:this.value,false:r}[`${this._isSome}`]}unwrapOrElse(r){return{true:this.value,false:r()}[`${this._isSome}`]}unwrapOrValueOf(r){return o(this._isSome,this.value,new r().valueOf())}eq(r){return this.isNone&&r.isNone?!0:this.isSome&&r.isSome?this.value===r.unwrap():!1}or(r){return o(this._isSome,this,r)}orElse(r){return o(this._isSome,this,r(this.value))}and(r){return o(this._isSome,r,this)}andThen(r){let t=o(this._isSome,this.value,this.value);return o(this._isSome,r(t),this)}getOrInsert(r){return this._isSome?this.value:this.setValue(r)}match(r,t){for(let[J,R]of r.entries())if(this._isSome&&this.value===J)return R();return t}expect(r){if(!this._isSome)throw r instanceof Error?r:new Error(r);return o(this._isSome,this.value,void 0)}toResult(r){return o(this._isSome,s(this.value),n(r))}toJSON(){return o(this._isSome,k(this.value),E())}toOptionString(){return o(this._isSome,`Some(${String(this.value)})`,"None()")}toString(){return this._isSome?String(this.value):"None"}removeValue(){let r=this.value;return this._isSome=!1,this.value=void 0,r}setValue(r){return this._isSome=!0,this.value=r,r}};function h(e){return e instanceof p}function I(e){return e instanceof p&&e.isSome===!0}function d(e){return e instanceof p&&e.isNone===!0}function u(e){return d(e)?e:c(e)?new p(!1,void 0):new p(!1,e)}function re(e){return e===void 0?u():i(e)}function te(e){return e==null?u():typeof e=="number"&&isNaN(e)?u():i(e)}function oe(e){return isNaN(e)?u():i(e)}function pe(e){if(h(e))return e;if(m(e))return S(e);throw new Error("Invalid Option instance")}var y=class e{constructor(r){this.value=v(r)?r.value:r}get isOk(){return!0}ok(){return this.value}get isErr(){return!1}err(){}match(r){return r.Ok(this.value)}toOption(){return i(this.value)}unwrap(r){return this.value}unwrapOr(r){return this.value}unwrapOrElse(r){return this.value}unwrapOrValueOf(r){return this.value}eq(r){return this.value===r.ok()}or(r){return this}orElse(r){return this}and(r){return r}clone(){return new e(this.value)}andThen(r){return r(this.value)}toString(){return`Ok(${String(this.value)})`}toJSON(){return{$class:"Result::Ok",value:this.value}}};function a(e){return e instanceof y||e instanceof T}function s(e){return a(e)?e:new y(e)}function b(e){return typeof e=="object"&&e!==null&&"$class"in e&&(e.$class==="Result::Ok"||e.$class==="Result::Err")}function v(e){return b(e)&&e.$class==="Result::Ok"}function w(e){return b(e)&&e.$class==="Result::Err"}function ve(e){return e.$class==="Result::Ok"?s(e.value):n(e.value)}var T=class e{constructor(r){this.error=w(r)?r.value:r}get isOk(){return!1}ok(){}get isErr(){return!0}err(){return this.error}toOption(){return u()}unwrap(r){throw r?typeof r=="function"?r(this.error):r:this.error}unwrapOr(r){return r}unwrapOrElse(r){return r()}unwrapOrValueOf(r){return new r().valueOf()}eq(r){return this.error===r.err()}or(r){return r}orElse(r){return r(this.error)}and(r){return this}clone(){return new e(this.error)}andThen(r){return this}match(r){return r.Err(this.error)}toString(){return`Err(${this.getErrorInstanceName()}${this.getErrorInstanceMessage()})`}toJSON(){return{$class:"Result::Err",value:this.error}}getErrorInstanceName(){return typeof this.error=="object"&&this.error!==null?this.error.constructor.name:"UnknownErrorInstance"}getErrorInstanceMessage(){return this.error instanceof Error?`: '${this.error.message}'`:`: '${JSON.stringify(this.error)}'`}};function n(e){return a(e)?e:new T(e)}async function x(e){let r=(await Promise.allSettled([e]))[0];return r.status==="fulfilled"?s(r.value):n(r.reason)}function Ce(e){return async(...r)=>{try{return x(e(...r))}catch(t){return n(t)}}}async function _e(e){try{return x(typeof e=="function"?e():e)}catch(r){return n(r)}}function Fe(e){return(...r)=>{try{return s(e(...r))}catch(t){return n(t)}}}function We(e){try{return s(e())}catch(r){return n(r)}}export{n as Err,T as ErrInstance,u as None,s as Ok,y as OkInstance,pe as Option,p as OptionBuilder,i as Some,o as asMapped,E as buildJsonNone,k as buildJsonSome,S as fromJsonOption,ve as fromJsonResult,w as isJsonErr,c as isJsonNone,v as isJsonOk,m as isJsonOption,b as isJsonResult,f as isJsonSome,d as isNone,h as isOption,a as isResult,I as isSome,oe as nanOption,te as nullishOptionWrap,l as optionNoneClass,O as optionSomeClass,_e as safeAsyncResult,Ce as safeAsyncResultBuilder,We as safeResult,Fe as safeResultBuilder,re as undefinedOptionWrap};
//# sourceMappingURL=index.js.map
{
"name": "@luolapeikko/result-option",
"version": "0.6.6",
"version": "1.0.0",
"description": "Rust style Result for TypeScript/Javascript",

@@ -11,5 +11,5 @@ "type": "module",

".": {
"types": "./dist/index.d.ts",
"require": "./dist/index.cjs",
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
"import": "./dist/index.js"
}

@@ -53,17 +53,18 @@ },

"devDependencies": {
"@stylistic/eslint-plugin": "^2.6.4",
"@types/chai": "^4.3.18",
"@types/chai-as-promised": "^7.1.8",
"@types/mocha": "^10.0.7",
"@types/node": "^18.19.46",
"@typescript-eslint/eslint-plugin": "^8.3.0",
"@typescript-eslint/parser": "^8.3.0",
"@stylistic/eslint-plugin": "^2.8.0",
"@stylistic/eslint-plugin-ts": "^2.8.0",
"@types/chai": "^5.0.0",
"@types/chai-as-promised": "^8.0.1",
"@types/mocha": "^10.0.8",
"@types/node": "^18.19.54",
"@typescript-eslint/eslint-plugin": "^8.8.0",
"@typescript-eslint/parser": "^8.8.0",
"c8": "^10.1.2",
"chai": "^5.1.1",
"chai-as-promised": "^8.0.0",
"eslint": "^8.57.0",
"eslint": "^8.57.1",
"eslint-config-prettier": "^9.1.0",
"eslint-config-standard": "^17.1.0",
"eslint-plugin-deprecation": "^3.0.0",
"eslint-plugin-jsdoc": "^48.11.0",
"eslint-plugin-jsdoc": "^50.3.1",
"eslint-plugin-prettier": "^5.2.1",

@@ -75,9 +76,9 @@ "eslint-plugin-sonarjs": "^0.23.0",

"ts-node": "^10.9.2",
"tsup": "^8.2.4",
"typedoc": "^0.26.6",
"typescript": "^5.5.4"
"tsup": "^8.3.0",
"typedoc": "^0.26.7",
"typescript": "^5.6.2"
},
"scripts": {
"doc": "typedoc",
"build": "tsup src/index.ts --format cjs,esm --dts --clean",
"build": "tsup src/index.ts --minify --sourcemap --format cjs,esm --dts --clean",
"test": "c8 mocha",

@@ -84,0 +85,0 @@ "coverage": "c8 report --reporter=lcovonly",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc