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
0
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.0 to 0.6.6

619

dist/index.d.ts

@@ -30,32 +30,2 @@ /**

/**
* Interface for the Or 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 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;
}
interface IClone<CloneType> {

@@ -85,47 +55,121 @@ /**

/**
* 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;
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;
}
/**
* 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> {
type ResultMatchSolver<OkType, ErrType, OkOutput, ErrOutput> = {
Ok: (value: OkType) => OkOutput;
Err: (err: ErrType) => ErrOutput;
};
interface IResultMatch<OkType, ErrType> {
/**
* Method to unwrap the value or throw an error
* @param {(err: ErrorType) => Error} err - optional function to transform the error
* 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).unwrap() // 2
* Err<number>(new Error('broken')).unwrap() // throws Error('broken')
* Some(2).unwrap() // 2
* None<number>().unwrap() // throws Error
* Ok<number>(2).match({
* Ok: (value) => value * 2,
* Err: (err) => 0
* }) // 4
*/
unwrap(err?: (err: ErrorType) => Error): ValueType;
match<OkOutput, ErrOutput>(solver: ResultMatchSolver<OkType, ErrType, OkOutput, ErrOutput>): OkOutput | ErrOutput;
}
type OptionMatchSolver<SomeType, Output> = Map<SomeType, () => Output>;
interface IOptionMatch<SomeType> {
/**
* Method to unwrap the value or if error return the default value
* @param defaultValue - default value to return
* 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',
* );
*/
unwrapOr<DefaultType>(defaultValue: DefaultType): DefaultType | ValueType;
match<Output>(solver: OptionMatchSolver<SomeType, Output>, defaultValue: Output): Output;
match<Output>(solver: OptionMatchSolver<SomeType, Output>): Output | undefined;
}
/**
* JSON representation of Some class
*/
type IJsonSome<SomeType> = {
$class: 'Option::Some';
value: SomeType;
};
/**
* JSON representation of None class
*/
type IJsonNone = {
$class: 'Option::None';
};
/**
* Option as JSON payload
*/
type IJsonOption<SomeType> = IJsonSome<SomeType> | IJsonNone;
/**
* JSON representation of Ok class
*/
type IJsonOk<OkType> = {
$class: 'Result::Ok';
value: OkType;
};
/**
* JSON representation of Err class
*/
type IJsonErr<ErrType> = {
$class: 'Result::Err';
value: ErrType;
};
/**
* Result as JSON payload
*/
type IJsonResult<OkType, ErrType> = IJsonOk<OkType> | IJsonErr<ErrType>;
/**
* Interface for the Or method
*/
interface IOr<BaseType, OutType extends BaseType> {
/**
* Method to unwrap the value or if error return default value from function
* @param {() => DefaultType} callbackFunc - function to return default value
* 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)
*/
unwrapOrElse<DefaultType>(callbackFunc: () => DefaultType): DefaultType | ValueType;
or<CompareType extends BaseType>(value: CompareType): OutType | CompareType;
}
interface IOrElse<BaseType, ValueType extends BaseType, ErrType = void> {
/**
* Method to unwrap the value or if error return default value from constructors valueOf
* @param constructorValueOf - constructor to return default value from valueOf
* 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)
*/
unwrapOrValueOf(constructorValueOf: ConstructorWithValueOf<ValueType>): ValueType;
orElse<ElseType extends BaseType>(callbackFunc: (value: ErrType) => ElseType): ValueType | ElseType;
}
interface OptionImplementation<SomeType> extends IUnWrap<SomeType, Error>, IEquals<Option>, IClone<Option<SomeType>>, IOr<Option, Option<SomeType>>, IOrElse<Option, Option<SomeType>>, IAnd<Option, Option<SomeType>>, IAndThen<SomeType, Option, INone<SomeType>> {
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> {
/**

@@ -146,11 +190,7 @@ * Returns true if the option is a Some value.

/**
* 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;
/**
* Returns the contained Some value, consuming the self value.
*
* Warning: currently TS can't change type of "this" (with asserts) and return value at the same time.
* https://github.com/microsoft/TypeScript/issues/41339
* @returns {IOption<SomeType>} copy of original Option
* @example

@@ -162,27 +202,13 @@ * const x = Some(2);

*/
take(): Option<SomeType>;
take(): IOption<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: Map<SomeType, () => Output>, defaultValue: Output): Output;
match<Output>(solver: Map<SomeType, () => Output>): Output | undefined;
/**
* Replace the actual value with the given one and returns the old Option.
*
* Warning: currently TS can't change type of "this" (with asserts) and return value at the same time.
* https://github.com/microsoft/TypeScript/issues/41339
* @param value new value
* @returns {Option<SomeType>} old Option
* @returns {IOption<SomeType>} old Option
* @see https://doc.rust-lang.org/std/option/enum.Option.html#method.replace
*/
replace(value: SomeType): Option<SomeType>;
replace(value: SomeType): IOption<SomeType>;
/**

@@ -203,9 +229,12 @@ * Inserts value into Option.

/**
* Converts Option to Result with the given error value if the option is None.
* @param err Error value if the option is None
* @returns {Result<SomeType, ErrType>} Result
* Convert Option to string
*/
toResult<ErrType>(err: ErrType): Result<SomeType, ErrType>;
toString(): `Some(${string})` | `None()`;
/**
* Convert Option to JSON
* @returns {IJsonOption<SomeType>} JSON representation
*/
toJSON(): IJsonOption<SomeType>;
}
interface ISome<SomeType> extends Omit<OptionImplementation<SomeType>, 'isNone' | 'isSome'> {
interface ISome<SomeType> extends Omit<OptionImplementation<SomeType>, 'isNone' | 'isSome' | 'toJSON'> {
/**

@@ -223,4 +252,9 @@ * Returns true if the option is a None value.

isSome: true;
/**
* Convert Option to JSON
* @returns {IJsonOption<SomeType>} JSON representation
*/
toJSON(): IJsonSome<SomeType>;
}
interface INone<SomeType> extends Omit<OptionImplementation<SomeType>, 'isNone' | 'isSome'> {
interface INone<SomeType> extends Omit<OptionImplementation<SomeType>, 'isNone' | 'isSome' | 'toJSON'> {
/**

@@ -238,5 +272,10 @@ * Returns true if the option is a None value.

isSome: false;
/**
* Convert Option to JSON
* @returns {IJsonOption<SomeType>} JSON representation
*/
toJSON(): IJsonNone;
}
/**
* Option represents an optional value: every Option is either Some and contains a value and type, or None which does not any type.
* IOption represents an optional value: every Option is either Some and contains a value and type, or None which does not any type.
* @template SomeType type of the value

@@ -257,6 +296,84 @@ * @example

*/
type Option<SomeType = unknown> = ISome<SomeType> | INone<SomeType>;
type IOption<SomeType = unknown> = ISome<SomeType> | INone<SomeType>;
interface IResultImplementation<OkType, ErrType> extends IUnWrap<OkType, ErrType>, IEquals<Result>, IOr<Result, Result<OkType, ErrType>>, IOrElse<Result, Result<OkType, ErrType>, ErrType>, IAnd<Result, Result<OkType, ErrType>>, IClone<Result<OkType, ErrType>>, IAndThen<OkType, Result, IErr<OkType, ErrType>> {
declare function None<SomeType>(noneInstance?: IJsonNone | INone<SomeType>): INone<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>;
/**
* Simple function to wrap a possible undefined value as None
* @template ValueType type of value
* @param value value to wrap
* @returns {IOption<ValueType>} - returns Some(value) or None()
* @example
* const valueOption: Option<number> = undefinedOptionWrap<number>(getNumValueOrUndefined());
*/
declare function undefinedOptionWrap<ValueType>(value: ValueType | undefined): IOption<ValueType>;
/**
* Simple function to wrap a possible null or undefined value as None
* @template ValueType type of value
* @param value value to wrap
* @returns {IOption<ValueType>} - returns Some(value) or None()
* @example
* const valueOption: Option<number> = nullishOptionWrap<number>(getNumValueOrNull());
*/
declare function nullishOptionWrap<ValueType>(value: ValueType | null | undefined): IOption<ValueType>;
/**
* Simple function to wrap a possible NaN value as None
* @template ValueType extends number
* @param value value to wrap
* @returns {IOption<ValueType>} - returns Some(value) or None()
* @example
* nanOption(parseInt(stringNumber, 10)) // returns Some(value) or None()
*/
declare function nanOption<ValueType extends number>(value: ValueType): IOption<ValueType>;
/**
* get Option from any instance types (Some, None, JsonOption)
* @param instance instance to convert
* @returns {IOption<SomeType>} Option instance
*/
declare function Option<SomeType>(instance: ISome<SomeType> | INone<SomeType> | IJsonOption<SomeType>): ISome<SomeType> | INone<SomeType>;
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> {
/**
* Try to get value, otherwise return undefined

@@ -294,23 +411,16 @@ * @returns {OkType | undefined} value or undefined

/**
* Solve the result with the given solver
* @template Output Type of the output
* @param solver solver to use
* @returns {Output} returns the output of the solver
* @example
* const res: Result<string, Error> = Ok<string, Error>('hello');
* const data: string = res.match({
* Ok: (value) => `${value} world`,
* Err: (err) => `${err.message} world`,
* });
* Convert result to option and discard the error type
*/
match<Output>(solver: {
Ok: (value: OkType) => Output;
Err: (err: ErrType) => Output;
}): Output;
toOption(): IOption<OkType>;
/**
* Convert result to option and discard the error type
* Convert result to string
*/
toOption(): Option<OkType>;
toString(): `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
*/
toJSON(): IJsonResult<OkType, ErrType>;
}
interface IOk<OkType, ErrType> extends Omit<IResultImplementation<OkType, ErrType>, 'isOk' | 'isErr' | 'ok' | 'err'> {
interface IOk<OkType, ErrType> extends Omit<IResultImplementation<OkType, ErrType>, 'isOk' | 'isErr' | 'ok' | 'err' | 'toOption' | 'toJSON'> {
/**

@@ -344,4 +454,13 @@ * Check that result is not an error

err(): undefined;
/**
* Convert result to option and discard the error type
*/
toOption(): ISome<OkType>;
/**
* Convert result to JSON {$class: 'Result::Ok', value: OkType} or {$class: 'Result::Err', value: ErrType}
* @returns {IJsonResult<OkType, ErrType>} JSON representation of the result
*/
toJSON(): IJsonOk<OkType>;
}
interface IErr<OkType, ErrType> extends Omit<IResultImplementation<OkType, ErrType>, 'isOk' | 'isErr' | 'ok' | 'err'> {
interface IErr<OkType, ErrType> extends Omit<IResultImplementation<OkType, ErrType>, 'isOk' | 'isErr' | 'ok' | 'err' | 'toJSON'> {
/**

@@ -375,2 +494,11 @@ * Check that result is not an error

err(): ErrType;
/**
* Convert result to option and discard the error type
*/
toOption(): INone<OkType>;
/**
* Convert result to JSON {$class: 'Result::Ok', value: OkType} or {$class: 'Result::Err', value: ErrType}
* @returns {IJsonResult<OkType, ErrType>} JSON representation of the result
*/
toJSON(): IJsonErr<ErrType>;
}

@@ -396,3 +524,3 @@ /**

*/
type Result<OkType = unknown, ErrType = unknown> = IOk<OkType, ErrType> | IErr<OkType, ErrType>;
type IResult<OkType = unknown, ErrType = unknown> = IOk<OkType, ErrType> | IErr<OkType, ErrType>;
/**

@@ -403,93 +531,58 @@ * Utility type for OkType or Result

*/
type ResultOrOkType<OkType, ErrType> = OkType | Result<OkType, ErrType>;
type IResultOrOkType<OkType, ErrType> = OkType | IResult<OkType, ErrType>;
/**
* ResultBuilder class for Result implementation
*/
declare class ResultBuilder<OkType, ErrType> implements IResultImplementation<OkType, ErrType> {
private readonly value;
private readonly error;
private readonly isNotError;
interface IToResult<ValueType> {
/**
* ResultBuilder constructor
* @param isNotError determines if the result is an error or not
* @param value actual value or error in the result
* Method to convert as Result
* @param err Result Error type if conversion fails.
* @returns {IResult<SomeType, ErrType>} Result
*/
constructor(isNotError: true, value: OkType);
constructor(isNotError: false, value: ErrType);
ok(): OkType | undefined;
get isOk(): boolean;
err(): ErrType | undefined;
get isErr(): boolean;
unwrap(err?: (err: ErrType) => Error): OkType;
unwrapOr<DefType>(defaultValue: DefType): DefType | OkType;
unwrapOrElse<DefType>(fn: () => DefType): DefType | OkType;
unwrapOrValueOf(BaseConstructor: ConstructorWithValueOf<OkType>): OkType;
match<Output>(solver: {
Ok: (value: OkType) => Output;
Err: (err: ErrType) => Output;
}): Output;
eq<OtherType extends Result>(other: OtherType): boolean;
and<CompareType extends Result>(value: CompareType): Result<OkType, ErrType> | CompareType;
andThen<OutType extends Result>(value: (val: OkType) => OutType): IErr<OkType, ErrType> | OutType;
or<CompareType extends Result>(value: CompareType): Result<OkType, ErrType> | CompareType;
orElse<ElseResult extends Result>(callbackFunc: (value: ErrType) => ElseResult): Result<OkType, ErrType> | ElseResult;
cloned(): Result<OkType, ErrType>;
toOption(): Option<OkType>;
toResult<ErrType>(err: ErrType): IResult<ValueType, ErrType>;
}
/**
* Type guard for Result interface
* @template OkType Type of the return value, default is unknown
* @template ErrType Type of the error, default is unknown
* @param {unknown} value unknown value
* @returns {boolean} true if value is Result
* Primitive classes provide a valueOf method that returns a value from an object.
* @template ValueType return type of the valueOf method
*/
declare function isResult<OkType = unknown, ErrType = unknown>(value: unknown): value is Result<OkType, ErrType>;
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>;
declare class OptionBuilder<SomeType> implements OptionImplementation<SomeType> {
private _isSome;
private value;
constructor(isSome: false);
constructor(isSome: true, value: SomeType);
get isNone(): boolean;
get isSome(): boolean;
expect(msgOrError: string | Error): SomeType;
unwrap(err?: ((err: Error) => Error) | undefined): SomeType;
unwrapOr<DefType>(def: DefType): DefType | SomeType;
unwrapOrElse<DefType>(fn: () => DefType): DefType | SomeType;
unwrapOrValueOf(BaseConstructor: ConstructorWithValueOf<SomeType>): SomeType;
take(): Option<SomeType>;
cloned(): Option<SomeType>;
eq<OtherType extends Option>(other: OtherType): boolean;
or<CompareType extends Option>(value: CompareType): Option<SomeType> | CompareType;
orElse<ElseResult extends Option>(callbackFunc: (value: void) => ElseResult): Option<SomeType> | ElseResult;
and<CompareType extends Option>(value: CompareType): Option<SomeType> | CompareType;
andThen<OutType extends Option>(callbackFunc: (val: SomeType) => OutType): OutType | INone<SomeType>;
replace(value: SomeType): Option<SomeType>;
insert(value: SomeType): SomeType;
getOrInsert(value: SomeType): SomeType;
match<Output>(solver: Map<SomeType, () => Output>, defaultValue?: Output | undefined): Output | undefined;
match<Output>(solver: Map<SomeType, () => Output>, defaultValue: Output): Output;
toResult<ErrType>(err: ErrType): Result<SomeType, ErrType>;
private toNone;
interface IUnWrap<ValueType, ErrorType> {
/**
* set the value of the option and change the state to Some
* @param value - the value to set
* @returns the value that was set
* 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
*/
private setValue;
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 Ok result or return if already a Result
* @template OkType ok type
* @template ErrType error type
* @param value - value to wrap or return if already a Result
* @returns {Result<OkType, ErrType>} - Result
* @example
* Ok<number>(2) // Result<number, unknown>
*/
declare function Ok<OkType = unknown, ErrType = unknown>(value: OkType | Result<OkType, ErrType>): Result<OkType, ErrType>;
/**
* Build Err result or return if already a Result

@@ -499,3 +592,3 @@ * @template OkType ok type

* @param error - error to wrap or return if already a Result
* @returns {Result<OkType, ErrType>} - Result
* @returns {IResult<OkType, ErrType>} - Result
* @example

@@ -505,31 +598,80 @@ * Err(2); // Result<unknown, number>

*/
declare function Err<OkType = unknown, ErrType = unknown>(error: ErrType | Result<OkType, ErrType>): Result<OkType, ErrType>;
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 None<SomeType>(): INone<SomeType>;
declare class ErrInstance<OkType, ErrType> implements IErr<OkType, ErrType> {
private readonly error;
readonly isOk = false;
readonly isErr = true;
constructor(error: ErrType | IJsonErr<ErrType>);
ok(): undefined;
err(): ErrType;
toOption(): INone<OkType>;
unwrap(err?: Error | ((err: ErrType) => Error) | undefined): OkType;
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;
toString(): `Err(${string})`;
toJSON(): IJsonErr<ErrType>;
private getErrorInstanceName;
private getErrorInstanceMessage;
}
declare function isJsonResult<OkType, ErrType>(json: unknown): json is IJsonResult<OkType, ErrType>;
declare function isJsonOk<OkType, ErrType>(json: unknown): json is IJsonOk<OkType>;
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: IJsonResult<OkType, ErrType>): IResult<OkType, ErrType>;
/**
* build safe wrapper for callback function
* @template TArgs function arguments
* @template OkType return type
* Build Ok result or return if already a Result
* @template OkType ok type
* @template ErrType error type
* @param func callback function
* @returns Result
* @param value - value to wrap or return if already a Result
* @returns {IResult<OkType, ErrType>} - Result
* @example
* const existsSync = safeResultBuilder(fs.existsSync);
* const result: Result<boolean> = existsSync('test.txt');
* Ok<number>(2) // Result<number, unknown>
*/
declare function safeResultBuilder<TArgs extends any[], OkType = unknown, ErrType = unknown>(func: (...args: TArgs) => ResultOrOkType<OkType, ErrType>): (...args: TArgs) => Result<OkType, ErrType>;
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 class OkInstance<OkType, ErrType> implements IOk<OkType, ErrType> {
private readonly value;
readonly isOk = true;
readonly isErr = false;
constructor(value: OkType | IJsonOk<OkType>);
ok(): OkType;
err(): undefined;
match<OkOutput, ErrOutput>(solver: ResultMatchSolver<OkType, ErrType, OkOutput, ErrOutput>): OkOutput;
toOption(): ISome<OkType>;
unwrap(_err?: ((err: ErrType) => Error) | undefined): 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;
toString(): `Ok(${string})`;
toJSON(): IJsonOk<OkType>;
}
/**
* safe wrapper for function
* @param func
* @template OkType return type
* @template ErrType error type
* @returns Result
* @example
* function test(): number {
* throw new Error('asd');
* }
* const value: Result<number> = safeResult(test);
* Type guard for Result interface
* @template OkType Type of the return value, default is unknown
* @template ErrType Type of the error, default is unknown
* @param {unknown} value unknown value
* @returns {boolean} true if value is Result
*/
declare function safeResult<OkType = unknown, ErrType = unknown>(func: () => ResultOrOkType<OkType, ErrType>): Result<OkType, ErrType>;
declare function isResult<OkType = unknown, ErrType = unknown>(value: unknown): value is IResult<OkType, ErrType>;

@@ -560,3 +702,3 @@ /**

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

@@ -571,25 +713,30 @@ * safe wrapper for async Promise

*/
declare function safeAsyncResult<OkType = unknown, ErrType = unknown>(func: Promise<ResultOrOkType<OkType, ErrType>> | (() => Promise<ResultOrOkType<OkType, ErrType>>)): Promise<Result<OkType, ErrType>>;
declare function safeAsyncResult<OkType = unknown, ErrType = unknown>(func: Promise<IResultOrOkType<OkType, ErrType>> | (() => Promise<IResultOrOkType<OkType, ErrType>>)): Promise<IResult<OkType, ErrType>>;
declare function Some<SomeType = unknown>(value: SomeType): ISome<SomeType>;
/**
* Simple function to wrap a possible undefined value as None
* @template ValueType type of value
* @param value value to wrap
* @returns {Option<ValueType>} - returns Some(value) or None()
* build safe wrapper for callback function
* @template TArgs function arguments
* @template OkType return type
* @template ErrType error type
* @param func callback function
* @returns Result
* @example
* const valueOption: Option<number> = undefinedOptionWrap<number>(getNumValueOrUndefined());
* const existsSync = safeResultBuilder(fs.existsSync);
* const result: Result<boolean> = existsSync('test.txt');
*/
declare function undefinedOptionWrap<ValueType>(value: ValueType | undefined): Option<ValueType>;
declare function safeResultBuilder<TArgs extends any[], OkType = unknown, ErrType = unknown>(func: (...args: TArgs) => IResultOrOkType<OkType, ErrType>): (...args: TArgs) => IResult<OkType, ErrType>;
/**
* Simple function to wrap a possible null or undefined value as None
* @template ValueType type of value
* @param value value to wrap
* @returns {Option<ValueType>} - returns Some(value) or None()
* safe wrapper for function
* @param func
* @template OkType return type
* @template ErrType error type
* @returns Result
* @example
* const valueOption: Option<number> = nullishOptionWrap<number>(getNumValueOrNull());
* function test(): number {
* throw new Error('asd');
* }
* const value: Result<number> = safeResult(test);
*/
declare function nullishOptionWrap<ValueType>(value: ValueType | null | undefined): Option<ValueType>;
declare function safeResult<OkType = unknown, ErrType = unknown>(func: () => IResultOrOkType<OkType, ErrType>): IResult<OkType, ErrType>;
export { type ConstructorWithValueOf, Err, type IErr, type INone, type IOk, type IResultImplementation, type ISome, None, Ok, type Option, OptionBuilder, type OptionImplementation, type Result, ResultBuilder, type ResultOrOkType, Some, type ValueOf, isResult, nullishOptionWrap, safeAsyncResult, safeAsyncResultBuilder, safeResult, safeResultBuilder, undefinedOptionWrap };
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 };

@@ -1,22 +0,32 @@

// src/Err.ts
function Err(error) {
if (isResult(error)) {
return error;
// src/option/Some.ts
function Some(value) {
if (isOption(value)) {
return value;
}
return new ResultBuilder(false, error);
return new OptionBuilder(true, value);
}
// src/Ok.ts
function Ok(value) {
if (isResult(value)) {
return value;
// src/option/JsonOption.ts
function fromJsonOption(json) {
if (json.$class === "Option::None") {
return None();
} else {
return Some(json.value);
}
return new ResultBuilder(true, 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/OptionBuilder.ts
// src/option/OptionBuilder.ts
var OptionBuilder = class _OptionBuilder {
constructor(isSome, value) {
this._isSome = isSome;
this.value = value;
this.value = isJsonOption(value) ? getJsonOptionValue(value) : value;
}

@@ -30,3 +40,3 @@ get isNone() {

expect(msgOrError) {
if (this._isSome) {
if (this.thisIsSome()) {
return this.value;

@@ -37,10 +47,16 @@ }

unwrap(err) {
if (this._isSome) {
if (this.thisIsSome()) {
return this.value;
}
const error = new Error("Option: No value was set");
throw err !== void 0 ? err(error) : error;
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._isSome) {
if (this.thisIsSome()) {
return this.value;

@@ -51,3 +67,3 @@ }

unwrapOrElse(fn) {
if (this._isSome) {
if (this.thisIsSome()) {
return this.value;

@@ -58,3 +74,3 @@ }

unwrapOrValueOf(BaseConstructor) {
if (this._isSome) {
if (this.thisIsSome()) {
return this.value;

@@ -66,7 +82,7 @@ }

const result = this.cloned();
this.toNone();
this.removeValue();
return result;
}
cloned() {
if (this._isSome) {
if (this.thisIsSome()) {
return new _OptionBuilder(true, this.value);

@@ -86,3 +102,3 @@ }

or(value) {
if (this._isSome) {
if (this.thisIsSome()) {
return this;

@@ -94,3 +110,3 @@ }

orElse(callbackFunc) {
if (this._isSome) {
if (this.thisIsSome()) {
return this;

@@ -101,3 +117,3 @@ }

and(value) {
if (!this._isSome) {
if (this.thisIsNone()) {
return this;

@@ -108,3 +124,3 @@ }

andThen(callbackFunc) {
if (this._isSome) {
if (this.thisIsSome()) {
return callbackFunc(this.value);

@@ -123,3 +139,3 @@ }

getOrInsert(value) {
if (!this._isSome) {
if (!this.thisIsSome()) {
return this.setValue(value);

@@ -138,3 +154,3 @@ }

toResult(err) {
if (this._isSome) {
if (this.thisIsSome()) {
return Ok(this.value);

@@ -144,6 +160,20 @@ }

}
toNone() {
this._isSome = false;
this.value = void 0;
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"
};
}
}
/**

@@ -159,125 +189,252 @@ * set the value of the option and change the state to Some

}
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/None.ts
function None() {
return new OptionBuilder(false);
// src/option/None.ts
function None(noneInstance) {
if (isOption(noneInstance)) {
return noneInstance;
}
return new OptionBuilder(false, noneInstance);
}
// src/Some.ts
function Some(value) {
return new OptionBuilder(true, value);
// 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/ResultBuilder.ts
var ResultBuilder = class _ResultBuilder {
constructor(isNotError, value) {
this.isNotError = isNotError;
if (isNotError) {
this.value = value;
} else {
this.error = value;
}
// 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.isNotError ? this.value : void 0;
return this.value;
}
get isOk() {
return this.isNotError;
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.isNotError ? this.error : void 0;
return this.error;
}
get isErr() {
return !this.isNotError;
toOption() {
return None();
}
unwrap(err) {
if (this.isNotError) {
return this.value;
}
if (this.error !== void 0) {
if (err !== void 0) {
if (err) {
if (typeof err === "function") {
throw err(this.error);
}
throw this.error;
throw err;
}
throw new TypeError("Result: No error was set");
throw this.error;
}
unwrapOr(defaultValue) {
if (this.isNotError) {
return this.value;
}
return defaultValue;
}
unwrapOrElse(fn) {
if (this.isNotError) {
return this.value;
}
return fn();
unwrapOrElse(callbackFunc) {
return callbackFunc();
}
unwrapOrValueOf(BaseConstructor) {
if (this.isNotError) {
return this.value;
}
return new BaseConstructor().valueOf();
}
match(solver) {
if (this.isNotError) {
return solver.Ok(this.value);
} else {
return solver.Err(this.error);
}
}
eq(other) {
if (this.isNotError) {
return other.isOk && this.value === other.ok();
}
return other.isErr && this.error === other.err();
return this.error === other.err();
}
and(value) {
if (!this.isNotError) {
return this;
}
return value;
}
andThen(value) {
if (!this.isNotError) {
return this;
}
return value(this.value);
}
or(value) {
if (this.isNotError) {
return this;
}
return value;
}
orElse(callbackFunc) {
if (this.isNotError) {
return this;
}
return callbackFunc(this.error);
}
and(_value) {
return this;
}
cloned() {
if (this.isNotError) {
return new _ResultBuilder(true, this.value);
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 new _ResultBuilder(false, this.error);
return "UnknownErrorInstance";
}
toOption() {
if (this.isNotError) {
return Some(this.value);
getErrorInstanceMessage() {
if (this.error instanceof Error) {
return `: '${this.error.message}'`;
}
return None();
return `: '${JSON.stringify(this.error)}'`;
}
};
function isResult(value) {
return value instanceof ResultBuilder;
// src/result/Err.ts
function Err(error) {
if (isResult(error)) {
return error;
}
return new ErrInstance(error);
}
// src/safeResult.ts
function safeResultBuilder(func) {
return (...args) => {
// 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 Ok(func(...args));
return promiseSettledAsResult(func(...args));
} catch (err) {

@@ -288,5 +445,5 @@ return Err(err);

}
function safeResult(func) {
async function safeAsyncResult(func) {
try {
return Ok(func());
return promiseSettledAsResult(typeof func === "function" ? func() : func);
} catch (err) {

@@ -297,7 +454,7 @@ return Err(err);

// src/safeAsyncResult.ts
function safeAsyncResultBuilder(func) {
return async (...args) => {
// src/result/safeResult.ts
function safeResultBuilder(func) {
return (...args) => {
try {
return Ok(await func(...args));
return Ok(func(...args));
} catch (err) {

@@ -308,5 +465,5 @@ return Err(err);

}
async function safeAsyncResult(func) {
function safeResult(func) {
try {
return Ok(await (typeof func === "function" ? func() : func));
return Ok(func());
} catch (err) {

@@ -316,24 +473,18 @@ return Err(err);

}
// src/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();
}
return Some(value);
}
export {
Err,
ErrInstance,
None,
Ok,
OkInstance,
Option,
OptionBuilder,
ResultBuilder,
Some,
fromJsonResult,
isJsonErr,
isJsonOk,
isJsonResult,
isOption,
isResult,
nanOption,
nullishOptionWrap,

@@ -340,0 +491,0 @@ safeAsyncResult,

{
"name": "@luolapeikko/result-option",
"version": "0.6.0",
"version": "0.6.6",
"description": "Rust style Result for TypeScript/Javascript",

@@ -52,9 +52,9 @@ "type": "module",

"devDependencies": {
"@stylistic/eslint-plugin": "^2.6.1",
"@types/chai": "^4.3.17",
"@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.43",
"@typescript-eslint/eslint-plugin": "^8.0.00",
"@typescript-eslint/parser": "^8.0.0",
"@types/node": "^18.19.46",
"@typescript-eslint/eslint-plugin": "^8.3.0",
"@typescript-eslint/parser": "^8.3.0",
"c8": "^10.1.2",

@@ -70,3 +70,3 @@ "chai": "^5.1.1",

"eslint-plugin-sonarjs": "^0.23.0",
"mocha": "^10.7.0",
"mocha": "^10.7.3",
"prettier": "^3.3.3",

@@ -76,3 +76,3 @@ "source-map-support": "^0.5.21",

"tsup": "^8.2.4",
"typedoc": "^0.26.5",
"typedoc": "^0.26.6",
"typescript": "^5.5.4"

@@ -79,0 +79,0 @@ },

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