Socket
Socket
Sign inDemoInstall

ts-results

Package Overview
Dependencies
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-results - npm Package Compare versions

Comparing version 3.0.0 to 3.1.0

esm/option.js

204

esm/index.js

@@ -1,203 +0,3 @@

/**
* Contains the error value
*/
// @ts-ignore
var Err = /** @class */ (function () {
function Err(val) {
if (!(this instanceof Err)) {
return new Err(val);
}
this.ok = false;
this.err = true;
this.val = val;
}
Err.prototype[Symbol.iterator] = function () {
return {
next: function () {
return { done: true, value: undefined };
}
};
};
/**
* @deprecated in favor of unwrapOr
* @see unwrapOr
*/
Err.prototype.else = function (val) {
return val;
};
Err.prototype.unwrapOr = function (val) {
return val;
};
Err.prototype.expect = function (msg) {
throw new Error(msg + " - Error: " + toString(this.val));
};
Err.prototype.unwrap = function () {
throw new Error("Tried to unwrap Error: " + toString(this.val));
};
Err.prototype.map = function (_mapper) {
return this;
};
Err.prototype.andThen = function (op) {
return this;
};
Err.prototype.mapErr = function (mapper) {
return new Err(mapper(this.val));
};
/** An empty Err */
Err.EMPTY = new Err(undefined);
return Err;
}());
export { Err };
/**
* Contains the success value
*/
// @ts-ignore
var Ok = /** @class */ (function () {
function Ok(val) {
if (!(this instanceof Ok)) {
return new Ok(val);
}
this.ok = true;
this.err = false;
this.val = val;
}
/**
* Helper function if you know you have an Ok<T> and T is iterable
*/
Ok.prototype[Symbol.iterator] = function () {
var obj = Object(this.val);
return Symbol.iterator in obj ? obj[Symbol.iterator]() : {
next: function () {
return { done: true, value: undefined };
}
};
};
/**
* @see unwrapOr
* @deprecated in favor of unwrapOr
*/
Ok.prototype.else = function (_val) {
return this.val;
};
Ok.prototype.unwrapOr = function (_val) {
return this.val;
};
Ok.prototype.expect = function (_msg) {
return this.val;
};
Ok.prototype.unwrap = function () {
return this.val;
};
Ok.prototype.map = function (mapper) {
return new Ok(mapper(this.val));
};
Ok.prototype.andThen = function (mapper) {
return mapper(this.val);
};
Ok.prototype.mapErr = function (_mapper) {
return this;
};
/**
* Returns the contained `Ok` value, but never throws.
* Unlike `unwrap()`, this method doesn't throw and is only callable on an Ok<T>
*
* Therefore, it can be used instead of `unwrap()` as a maintainability safeguard
* that will fail to compile if the error type of the Result is later changed to an error that can actually occur.
*
* (this is the `into_ok()` in rust)
*/
Ok.prototype.safeUnwrap = function () {
return this.val;
};
Ok.EMPTY = new Ok(undefined);
return Ok;
}());
export { Ok };
export var Result;
(function (Result) {
/**
* Parse a set of `Result`s, returning an array of all `Ok` values.
* Short circuits with the first `Err` found, if any
*/
function all() {
var results = [];
for (var _i = 0; _i < arguments.length; _i++) {
results[_i] = arguments[_i];
}
var okResult = [];
for (var _a = 0, results_1 = results; _a < results_1.length; _a++) {
var result = results_1[_a];
if (result.ok) {
okResult.push(result.val);
}
else {
return result;
}
}
return new Ok(okResult);
}
Result.all = all;
/**
* Parse a set of `Result`s, short-circuits when an input value is `Ok`.
* If no `Ok` is found, returns an `Err` containing the collected error values
*/
function any() {
var results = [];
for (var _i = 0; _i < arguments.length; _i++) {
results[_i] = arguments[_i];
}
var errResult = [];
// short-circuits
for (var _a = 0, results_2 = results; _a < results_2.length; _a++) {
var result = results_2[_a];
if (result.ok) {
return result;
}
else {
errResult.push(result.val);
}
}
// it must be a Err
return new Err(errResult);
}
Result.any = any;
/**
* Wrap an operation that may throw an Error (`try-catch` style) into checked exception style
* @param op The operation function
*/
function wrap(op) {
try {
return new Ok(op());
}
catch (e) {
return new Err(e);
}
}
Result.wrap = wrap;
/**
* Wrap an async operation that may throw an Error (`try-catch` style) into checked exception style
* @param op The operation function
*/
function wrapAsync(op) {
try {
return op().then(function (val) { return new Ok(val); }).catch(function (e) { return new Err(e); });
}
catch (e) {
return Promise.resolve(new Err(e));
}
}
Result.wrapAsync = wrapAsync;
})(Result || (Result = {}));
function toString(val) {
var value = String(val);
if (value === '[object Object]') {
try {
value = JSON.stringify(val);
}
catch (_a) {
}
}
return value;
}
var x = Result.all(Ok(3), Err(5));
export * from './result';
export * from './option';
//# sourceMappingURL=index.js.map
import { of } from 'rxjs';
import { filter, map, mergeMap, switchMap } from 'rxjs/operators';
import { Err, Ok } from '../index';
import { filter, map, mergeMap, switchMap, tap } from 'rxjs/operators';
import { Ok, Result } from '../index';
export function resultMap(mapper) {

@@ -58,3 +58,3 @@ return function (source) {

}), map(function (result) {
if (result instanceof Ok || result instanceof Err) {
if (Result.isResult(result)) {
return result;

@@ -78,3 +78,3 @@ }

}), map(function (result) {
if (result instanceof Ok || result instanceof Err) {
if (Result.isResult(result)) {
return result;

@@ -98,2 +98,20 @@ }

}
export function tapResultErr(tapFn) {
return function (source) {
return source.pipe(tap(function (r) {
if (!r.ok) {
tapFn(r.val);
}
}));
};
}
export function tapResultOk(tapFn) {
return function (source) {
return source.pipe(tap(function (r) {
if (r.ok) {
tapFn(r.val);
}
}));
};
}
//# sourceMappingURL=index.js.map

@@ -1,142 +0,3 @@

interface BaseResult<T, E> extends Iterable<T extends Iterable<infer U> ? U : never> {
/** `true` when the result is Ok */ readonly ok: boolean;
/** `true` when the result is Err */ readonly err: boolean;
/**
* Returns the contained `Ok` value, if exists. Throws an error if not.
* @param msg the message to throw if no Ok value.
*/
expect(msg: string): T;
/**
* Returns the contained `Ok` value.
* Because this function may throw, its use is generally discouraged.
* Instead, prefer to handle the `Err` case explicitly.
*
* Throws if the value is an `Err`, with a message provided by the `Err`'s value.
*/
unwrap(): T;
/**
* Returns the contained `Ok` value or a provided default.
*
* @see unwrapOr
* @deprecated in favor of unwrapOr
*/
else<T2>(val: T2): T | T2;
/**
* Returns the contained `Ok` value or a provided default.
*
* (This is the `unwrap_or` in rust)
*/
unwrapOr<T2>(val: T2): T | T2;
/**
* Calls `mapper` if the result is `Ok`, otherwise returns the `Err` value of self.
* This function can be used for control flow based on `Result` values.
*/
andThen<T2, E2>(mapper: (val: T) => Result<T2, E2>): Result<T2, E | E2>;
/**
* Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a contained `Ok` value,
* leaving an `Err` value untouched.
*
* This function can be used to compose the results of two functions.
*/
map<U>(mapper: (val: T) => U): Result<U, E>;
/**
* Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a contained `Err` value,
* leaving an `Ok` value untouched.
*
* This function can be used to pass through a successful result while handling an error.
*/
mapErr<F>(mapper: (val: E) => F): Result<T, F>;
}
export declare function Err<E>(val: E): Err<E>;
/**
* Contains the error value
*/
export declare class Err<E> implements BaseResult<never, E> {
/** An empty Err */
static readonly EMPTY: Err<void>;
readonly ok: false;
readonly err: true;
readonly val: E;
[Symbol.iterator](): Iterator<never, never, any>;
constructor(val: E);
/**
* @deprecated in favor of unwrapOr
* @see unwrapOr
*/
else<T2>(val: T2): T2;
unwrapOr<T2>(val: T2): T2;
expect(msg: string): never;
unwrap(): never;
map<T2>(_mapper: (val: never) => T2): Err<E>;
andThen<T2, E2>(op: (val: never) => Result<T2, E2>): Err<E>;
mapErr<E2>(mapper: (err: E) => E2): Err<E2>;
}
export declare function Ok<T>(val: T): Ok<T>;
/**
* Contains the success value
*/
export declare class Ok<T> implements BaseResult<T, never> {
static readonly EMPTY: Ok<void>;
readonly ok: true;
readonly err: false;
readonly val: T;
/**
* Helper function if you know you have an Ok<T> and T is iterable
*/
[Symbol.iterator](): Iterator<T extends Iterable<infer U> ? U : never>;
constructor(val: T);
/**
* @see unwrapOr
* @deprecated in favor of unwrapOr
*/
else(_val: unknown): T;
unwrapOr(_val: unknown): T;
expect(_msg: string): T;
unwrap(): T;
map<T2>(mapper: (val: T) => T2): Ok<T2>;
andThen<T2, E2>(mapper: (val: T) => Result<T2, E2>): Result<T2, E2>;
mapErr<E2>(_mapper: (err: never) => E2): Ok<T>;
/**
* Returns the contained `Ok` value, but never throws.
* Unlike `unwrap()`, this method doesn't throw and is only callable on an Ok<T>
*
* Therefore, it can be used instead of `unwrap()` as a maintainability safeguard
* that will fail to compile if the error type of the Result is later changed to an error that can actually occur.
*
* (this is the `into_ok()` in rust)
*/
safeUnwrap(): T;
}
export declare type Result<T, E> = (Ok<T> | Err<E>) & BaseResult<T, E>;
export declare type ResultOkType<T extends Result<any, any>> = T extends Result<infer U, any> ? U : never;
export declare type ResultErrType<T extends Result<any, any>> = T extends Result<any, infer U> ? U : never;
export declare type ResultOkTypes<T extends Result<any, any>[]> = {
[key in keyof T]: T[key] extends Result<infer U, any> ? U : never;
};
export declare type ResultErrTypes<T extends Result<any, any>[]> = {
[key in keyof T]: T[key] extends Result<any, infer U> ? U : never;
};
export declare namespace Result {
/**
* Parse a set of `Result`s, returning an array of all `Ok` values.
* Short circuits with the first `Err` found, if any
*/
function all<T extends Result<any, any>[]>(...results: T): Result<ResultOkTypes<T>, ResultErrTypes<T>[number]>;
/**
* Parse a set of `Result`s, short-circuits when an input value is `Ok`.
* If no `Ok` is found, returns an `Err` containing the collected error values
*/
function any<T extends Result<any, any>[]>(...results: T): Result<ResultOkTypes<T>[number], ResultErrTypes<T>>;
/**
* Wrap an operation that may throw an Error (`try-catch` style) into checked exception style
* @param op The operation function
*/
function wrap<T, E = unknown>(op: () => T): Result<T, E>;
/**
* Wrap an async operation that may throw an Error (`try-catch` style) into checked exception style
* @param op The operation function
*/
function wrapAsync<T, E = unknown>(op: () => Promise<T>): Promise<Result<T, E>>;
}
export {};
export * from './result';
export * from './option';
//# sourceMappingURL=index.d.ts.map

@@ -7,3 +7,3 @@ (function (factory) {

else if (typeof define === "function" && define.amd) {
define(["require", "exports"], factory);
define(["require", "exports", "tslib", "./result", "./option"], factory);
}

@@ -13,206 +13,6 @@ })(function (require, exports) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.Result = exports.Ok = exports.Err = void 0;
/**
* Contains the error value
*/
// @ts-ignore
var Err = /** @class */ (function () {
function Err(val) {
if (!(this instanceof Err)) {
return new Err(val);
}
this.ok = false;
this.err = true;
this.val = val;
}
Err.prototype[Symbol.iterator] = function () {
return {
next: function () {
return { done: true, value: undefined };
}
};
};
/**
* @deprecated in favor of unwrapOr
* @see unwrapOr
*/
Err.prototype.else = function (val) {
return val;
};
Err.prototype.unwrapOr = function (val) {
return val;
};
Err.prototype.expect = function (msg) {
throw new Error(msg + " - Error: " + toString(this.val));
};
Err.prototype.unwrap = function () {
throw new Error("Tried to unwrap Error: " + toString(this.val));
};
Err.prototype.map = function (_mapper) {
return this;
};
Err.prototype.andThen = function (op) {
return this;
};
Err.prototype.mapErr = function (mapper) {
return new Err(mapper(this.val));
};
/** An empty Err */
Err.EMPTY = new Err(undefined);
return Err;
}());
exports.Err = Err;
/**
* Contains the success value
*/
// @ts-ignore
var Ok = /** @class */ (function () {
function Ok(val) {
if (!(this instanceof Ok)) {
return new Ok(val);
}
this.ok = true;
this.err = false;
this.val = val;
}
/**
* Helper function if you know you have an Ok<T> and T is iterable
*/
Ok.prototype[Symbol.iterator] = function () {
var obj = Object(this.val);
return Symbol.iterator in obj ? obj[Symbol.iterator]() : {
next: function () {
return { done: true, value: undefined };
}
};
};
/**
* @see unwrapOr
* @deprecated in favor of unwrapOr
*/
Ok.prototype.else = function (_val) {
return this.val;
};
Ok.prototype.unwrapOr = function (_val) {
return this.val;
};
Ok.prototype.expect = function (_msg) {
return this.val;
};
Ok.prototype.unwrap = function () {
return this.val;
};
Ok.prototype.map = function (mapper) {
return new Ok(mapper(this.val));
};
Ok.prototype.andThen = function (mapper) {
return mapper(this.val);
};
Ok.prototype.mapErr = function (_mapper) {
return this;
};
/**
* Returns the contained `Ok` value, but never throws.
* Unlike `unwrap()`, this method doesn't throw and is only callable on an Ok<T>
*
* Therefore, it can be used instead of `unwrap()` as a maintainability safeguard
* that will fail to compile if the error type of the Result is later changed to an error that can actually occur.
*
* (this is the `into_ok()` in rust)
*/
Ok.prototype.safeUnwrap = function () {
return this.val;
};
Ok.EMPTY = new Ok(undefined);
return Ok;
}());
exports.Ok = Ok;
var Result;
(function (Result) {
/**
* Parse a set of `Result`s, returning an array of all `Ok` values.
* Short circuits with the first `Err` found, if any
*/
function all() {
var results = [];
for (var _i = 0; _i < arguments.length; _i++) {
results[_i] = arguments[_i];
}
var okResult = [];
for (var _a = 0, results_1 = results; _a < results_1.length; _a++) {
var result = results_1[_a];
if (result.ok) {
okResult.push(result.val);
}
else {
return result;
}
}
return new Ok(okResult);
}
Result.all = all;
/**
* Parse a set of `Result`s, short-circuits when an input value is `Ok`.
* If no `Ok` is found, returns an `Err` containing the collected error values
*/
function any() {
var results = [];
for (var _i = 0; _i < arguments.length; _i++) {
results[_i] = arguments[_i];
}
var errResult = [];
// short-circuits
for (var _a = 0, results_2 = results; _a < results_2.length; _a++) {
var result = results_2[_a];
if (result.ok) {
return result;
}
else {
errResult.push(result.val);
}
}
// it must be a Err
return new Err(errResult);
}
Result.any = any;
/**
* Wrap an operation that may throw an Error (`try-catch` style) into checked exception style
* @param op The operation function
*/
function wrap(op) {
try {
return new Ok(op());
}
catch (e) {
return new Err(e);
}
}
Result.wrap = wrap;
/**
* Wrap an async operation that may throw an Error (`try-catch` style) into checked exception style
* @param op The operation function
*/
function wrapAsync(op) {
try {
return op().then(function (val) { return new Ok(val); }).catch(function (e) { return new Err(e); });
}
catch (e) {
return Promise.resolve(new Err(e));
}
}
Result.wrapAsync = wrapAsync;
})(Result = exports.Result || (exports.Result = {}));
function toString(val) {
var value = String(val);
if (value === '[object Object]') {
try {
value = JSON.stringify(val);
}
catch (_a) {
}
}
return value;
}
var x = Result.all(Ok(3), Err(5));
var tslib_1 = require("tslib");
tslib_1.__exportStar(require("./result"), exports);
tslib_1.__exportStar(require("./option"), exports);
});
//# sourceMappingURL=index.js.map
{
"name": "ts-results",
"version": "3.0.0",
"description": "A typescript implementation of Rust's Result object.",
"version": "3.1.0",
"description": "A typescript implementation of Rust's Result and Option objects.",
"main": "index.js",
"module": "./esm/index.js",
"types": "index.d.ts",
"keywords": ["typescript", "rust", "errors", "result"],
"author": "Aidan Grant",
"keywords": [
"typescript",
"rust",
"errors",
"ok",
"err",
"result",
"option",
"some",
"none"
],
"author": "Vultix",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/vultix/ts-result"
"url": "https://github.com/vultix/ts-results"
},
"readme": "README.md"
}
# ts-results
A typescript implementation of [Rust's Result](https://doc.rust-lang.org/std/result/) object. Brings compile-time error checking to typescript.
*Note: This is the documentation for the newly released `ts-results@2.0.0` with breaking changes. To see breaking changes, go to [CHANGELOG.md](https://github.com/vultix/ts-results/blob/master/CHANGELOG.md)*
A typescript implementation of Rust's [Result](https://doc.rust-lang.org/std/result/)
and [Option](https://doc.rust-lang.org/std/option/) objects.
Brings compile-time error checking and optional values to typescript.
## Contents
* [Installation](#installation)
* [Example](#example)
* [Usage](#usage)
* [Creation](#creation)
* [Type Safety](#type-safety)
* [Unwrap](#unwrap)
* [Expect](#expect)
* [Map, MapErr](#map-and-maperr)
* [Else](#else)
* [UnwrapOr](#unwrapor)
* [Empty](#empty)
* [Combining Results](#combining-results)
* [Result.all](#result-all)
* [Result.any](#result-any)
* [Usage with rxjs](#usage-with-rxjs)
* [resultMap](#resultmap)
* [resultMapErr](#resultmaperr)
* [resultMapTo](#resultmapto)
* [resultMapErrTo](#resultmapto)
* [elseMap](#elsemap)
* [elseMapTo](#elsemapto)
* [resultSwitchMap, resultMergeMap](#resultswitchmap-and-resultmergemap)
* [filterResultOk](#filterresultok)
* [filterResultErr](#filterresulterr)
- [Installation](#installation)
- [Example](#example)
- [Result Example](#result-example)
- [Option Example](#option-example)
- [Usage](#usage)
- [Creation](#creation)
- [Type Safety](#type-safety)
- [Unwrap](#unwrap)
- [Expect](#expect)
- [Map, MapErr](#map-and-maperr)
- [Else](#else)
- [UnwrapOr](#unwrapor)
- [Empty](#empty)
- [Combining Results](#combining-results)
- [Result.all](#result-all)
- [Result.any](#result-any)
- [Usage with rxjs](#usage-with-rxjs)
- [resultMap](#resultmap)
- [resultMapErr](#resultmaperr)
- [resultMapTo](#resultmapto)
- [resultMapErrTo](#resultmapto)
- [elseMap](#elsemap)
- [elseMapTo](#elsemapto)
- [resultSwitchMap, resultMergeMap](#resultswitchmap-and-resultmergemap)
- [filterResultOk](#filterresultok)
- [filterResultErr](#filterresulterr)
## Installation
```bash
$ npm install ts-results
```
or
```bash

@@ -42,5 +50,9 @@ $ yarn add ts-results

## Example
### Result Example
Convert this:
```typescript
import {existsSync, readFileSync} from 'fs';
import { existsSync, readFileSync } from 'fs';

@@ -55,2 +67,3 @@ function readFile(path: string): string {

}
// This line may fail unexpectedly without warnings from typescript

@@ -61,5 +74,6 @@ const text = readFile('test.txt');

To this:
```typescript
import {existsSync, readFileSync} from 'fs';
import {Ok, Err, Result} from 'ts-results';
import { existsSync, readFileSync } from 'fs';
import { Ok, Err, Result } from 'ts-results';

@@ -70,3 +84,3 @@ function readFile(path: string): Result<string, 'invalid path'> {

} else {
return new Err("invalid path"); // new is optional here
return new Err('invalid path'); // new is optional here
}

@@ -86,7 +100,55 @@ }

### Option Example
Convert this:
```typescript
declare function getLoggedInUsername(): string | undefined;
declare function getImageURLForUsername(username: string): string | undefined;
function getLoggedInImageURL(): string | undefined {
const username = getLoggedInUsername();
if (!username) {
return undefined;
}
return getImageURLForUsername(username);
}
const stringUrl = getLoggedInImageURL();
const optionalUrl = stringUrl ? new URL(stringUrl) : undefined;
console.log(optionalUrl);
```
To this:
```typescript
import { Option, Some, None } from 'ts-results';
declare function getLoggedInUsername(): Option<string>;
declare function getImageForUsername(username: string): Option<string>;
function getLoggedInImage(): Option<string> {
return getLoggedInUsername().andThen(getImageForUsername);
}
const optionalUrl = getLoggedInImage().map((url) => new URL(stringUrl));
console.log(optionalUrl); // Some(URL('...'))
// To extract the value, do this:
if (optionalUrl.some) {
const url: URL = optionalUrl.val;
}
```
## Usage
```typescript
import { Result, Err, Ok } from 'ts-results';
```
#### Creation
```typescript

@@ -98,6 +160,6 @@ let okResult: Result<number, Error> = Ok(10);

let errorResult2 = Ok<number, Error>(new Error('bad number!')); // Exact same as above
```
#### Type Safety
```typescript

@@ -123,5 +185,6 @@ let result = Ok<number, Error>(1);

#### Unwrap
```typescript
let goodResult = new Ok(1);
let badResult = new Err(new Error("something went wrong"));
let badResult = new Err(new Error('something went wrong'));

@@ -133,5 +196,6 @@ goodResult.unwrap(); // 1

#### Expect
```typescript
let goodResult = Ok<number, Error>(1);
let badResult = Err<number, Error>(new Error("something went wrong"));
let badResult = Err<number, Error>(new Error('something went wrong'));

@@ -143,20 +207,29 @@ goodResult.expect('goodResult should be a number'); // 1

#### Map and MapErr
```typescript
let goodResult = Ok(1);
let badResult = Err(new Error("something went wrong"));
let badResult = Err(new Error('something went wrong'));
goodResult.map(num => num + 1).unwrap(); // 2
badResult.map(num => num + 1).unwrap(); // throws Error("something went wrong")
goodResult.map((num) => num + 1).unwrap(); // 2
badResult.map((num) => num + 1).unwrap(); // throws Error("something went wrong")
goodResult.map(num => num + 1).mapErr(err => new Error('mapped')).unwrap(); // 2
badResult.map(num => num + 1).mapErr(err => new Error('mapped')).unwrap(); // throws Error("mapped")
goodResult
.map((num) => num + 1)
.mapErr((err) => new Error('mapped'))
.unwrap(); // 2
badResult
.map((num) => num + 1)
.mapErr((err) => new Error('mapped'))
.unwrap(); // throws Error("mapped")
```
#### Else
Deprecated in favor of unwrapOr
#### UnwrapOr
```typescript
let goodResult = Ok(1);
let badResult = Err(new Error("something went wrong"));
let badResult = Err(new Error('something went wrong'));

@@ -168,2 +241,3 @@ goodResult.unwrapOr(5); // 1

#### Empty
```typescript

@@ -174,3 +248,3 @@ function checkIsValid(isValid: boolean): Result<void, Error> {

} else {
return new Err(new Error("Not valid"))
return new Err(new Error('Not valid'));
}

@@ -181,6 +255,9 @@ }

#### Combining Results
`ts-results` has two helper functions for operating over n `Result` objects.
##### Result.all
Either returns all of the `Ok` values, or the first `Err` value
```typescript

@@ -193,6 +270,8 @@ let pizzaResult: Result<Pizza, GetPizzaError> = getPizzaSomehow();

let [pizza, toppings] = result.unwrap(); // pizza is a Pizza, toppings is a Toppings. Could throw GetPizzaError or GetToppingsError.
```
```
##### Result.any
Either returns the first `Ok` value, or all `Err` values
```typescript

@@ -203,15 +282,18 @@ let url1: Result<string, Error1> = attempt1();

let result = Result.all(url1, url2, url3); // Result<string, Error1 | Error2 | Error3>
let result = Result.any(url1, url2, url3); // Result<string, Error1 | Error2 | Error3>
let url = result.unwrap(); // At least one attempt gave us a successful url
```
```
## Usage with rxjs
#### resultMap
Allows you to do the same actions as the normal [rxjs map](http://reactivex.io/documentation/operators/map.html) operator on a stream of Result objects.
#### resultMap
Allows you to do the same actions as the normal [rxjs map](http://reactivex.io/documentation/operators/map.html)
operator on a stream of Result objects.
```typescript
import {of, Observable} from 'rxjs';
import {Ok, Err, Result} from 'ts-results';
import {resultMap} from 'ts-results/rxjs-operators';
import { of, Observable } from 'rxjs';
import { Ok, Err, Result } from 'ts-results';
import { resultMap } from 'ts-results/rxjs-operators';

@@ -221,20 +303,22 @@ const obs$: Observable<Result<number, Error>> = of(Ok(5), Err('uh oh'));

const greaterThanZero = obs$.pipe(
resultMap(number => number > 0), // Doubles the value
resultMap((number) => number > 0), // Doubles the value
); // Has type Observable<Result<boolean, 'uh oh'>>
greaterThanZero.subscribe(result => {
if (result.ok) {
console.log('Was greater than zero: ' + result.val);
} else {
console.log('Got Error Message: ' + result.val);
}
greaterThanZero.subscribe((result) => {
if (result.ok) {
console.log('Was greater than zero: ' + result.val);
} else {
console.log('Got Error Message: ' + result.val);
}
});
// Logs the following:
// Logs the following:
// Got number: 10
// Got Error Message: uh oh
```
#### resultMapErr
```typescript
import {resultMapErr} from 'ts-results/rxjs-operators';
import { resultMapErr } from 'ts-results/rxjs-operators';
```

@@ -245,21 +329,27 @@

#### resultMapTo
```typescript
import {resultMapTo} from 'ts-results/rxjs-operators';
import { resultMapTo } from 'ts-results/rxjs-operators';
```
Behaves the same as [resultMap](#resultmap), but takes a value instead of a function.
#### resultMapErrTo
```typescript
import {resultMapErrTo} from 'ts-results/rxjs-operators';
import { resultMapErrTo } from 'ts-results/rxjs-operators';
```
Behaves the same as [resultMapErr](#resultmaperr), but takes a value instead of a function.
#### elseMap
Allows you to turn a stream of Result objects into a stream of values, transforming any errors into a value.
Similar to calling the [else](#else) function, but works on a stream of Result objects.
Similar to calling the [else](#else) function, but works on a stream of Result objects.
```typescript
import {of, Observable} from 'rxjs';
import {Ok, Err, Result} from 'ts-results';
import {elseMap} from 'ts-results/rxjs-operators';
import { of, Observable } from 'rxjs';
import { Ok, Err, Result } from 'ts-results';
import { elseMap } from 'ts-results/rxjs-operators';

@@ -269,11 +359,11 @@ const obs$: Observable<Result<number, Error>> = of(Ok(5), Err(new Error('uh oh')));

const doubled = obs$.pipe(
elseMap(err => {
console.log('Got error: ' + err.message);
return -1;
})
elseMap((err) => {
console.log('Got error: ' + err.message);
return -1;
}),
); // Has type Observable<number>
doubled.subscribe(number => {
console.log('Got number: ' + number);
doubled.subscribe((number) => {
console.log('Got number: ' + number);
});

@@ -288,17 +378,26 @@

#### elseMapTo
```typescript
import {elseMapTo} from 'ts-results/rxjs-operators';
import { elseMapTo } from 'ts-results/rxjs-operators';
```
Behaves the same as [elseMap](#elsemap), but takes a value instead of a function.
#### resultSwitchMap and resultMergeMap
Allows you to do the same actions as the normal [rxjs switchMap](https://www.learnrxjs.io/operators/transformation/switchmap.html) and [rxjs switchMap](https://www.learnrxjs.io/operators/transformation/mergemap.html) operator on a stream of Result objects.
Merging or switching from a stream of `Result<T, E>` objects onto a stream of `<T2>` objects turns the stream into a stream of `Result<T2, E>` objects.
Allows you to do the same actions as the
normal [rxjs switchMap](https://www.learnrxjs.io/operators/transformation/switchmap.html)
and [rxjs switchMap](https://www.learnrxjs.io/operators/transformation/mergemap.html) operator on a stream of Result
objects.
Merging or switching from a stream of `Result<T, E>` objects onto a stream of `Result<T2, E2>` objects turn the stream into a stream of `Result<T2, E | T2>` objects.
Merging or switching from a stream of `Result<T, E>` objects onto a stream of `<T2>` objects turns the stream into a
stream of `Result<T2, E>` objects.
Merging or switching from a stream of `Result<T, E>` objects onto a stream of `Result<T2, E2>` objects turn the stream
into a stream of `Result<T2, E | T2>` objects.
```typescript
import {of, Observable} from 'rxjs';
import {Ok, Err, Result} from 'ts-results';
import {resultMergeMap} from 'ts-results/rxjs-operators';
import { of, Observable } from 'rxjs';
import { Ok, Err, Result } from 'ts-results';
import { resultMergeMap } from 'ts-results/rxjs-operators';

@@ -310,15 +409,15 @@ const obs$: Observable<Result<number, Error>> = of(new Ok(5), new Err(new Error('uh oh')));

const test$ = obs$.pipe(
resultMergeMap(number => {
console.log('Got number: ' + number);
resultMergeMap((number) => {
console.log('Got number: ' + number);
return obs2$;
})
return obs2$;
}),
); // Has type Observable<Result<string, CustomError | Error>>
test$.subscribe(result => {
if (result.ok) {
console.log('Got string: ' + result.val);
} else {
console.log('Got error: ' + result.val.message);
}
test$.subscribe((result) => {
if (result.ok) {
console.log('Got string: ' + result.val);
} else {
console.log('Got error: ' + result.val.message);
}
});

@@ -333,19 +432,17 @@

#### filterResultOk
#### filterResultOk
Converts an `Observable<Result<T, E>>` to an `Observble<T>` by filtering out the Errs and mapping to the Ok values.
```typescript
import {of, Observable} from 'rxjs';
import {Ok, Err, Result} from 'ts-results';
import {filterResultOk} from 'ts-results/rxjs-operators';
import { of, Observable } from 'rxjs';
import { Ok, Err, Result } from 'ts-results';
import { filterResultOk } from 'ts-results/rxjs-operators';
const obs$: Observable<Result<number, Error>> = of(new Ok(5), new Err(new Error('uh oh')));
const test$ = obs$.pipe(
filterResultOk()
); // Has type Observable<number>
const test$ = obs$.pipe(filterResultOk()); // Has type Observable<number>
test$.subscribe(result => {
console.log('Got number: ' + result);
test$.subscribe((result) => {
console.log('Got number: ' + result);
});

@@ -355,21 +452,19 @@

// Got number: 5
```
#### filterResultErr
Converts an `Observable<Result<T, E>>` to an `Observble<T>` by filtering out the Oks and mapping to the error values.
```typescript
import {of, Observable} from 'rxjs';
import {Ok, Err, Result} from 'ts-results';
import {filterResultOk} from 'ts-results/rxjs-operators';
import { of, Observable } from 'rxjs';
import { Ok, Err, Result } from 'ts-results';
import { filterResultOk } from 'ts-results/rxjs-operators';
const obs$: Observable<Result<number, Error>> = of(new Ok(5), new Err(new Error('uh oh')));
const test$ = obs$.pipe(
filterResultOk()
); // Has type Observable<number>
const test$ = obs$.pipe(filterResultOk()); // Has type Observable<number>
test$.subscribe(result => {
console.log('Got number: ' + result);
test$.subscribe((result) => {
console.log('Got number: ' + result);
});

@@ -379,3 +474,2 @@

// Got number: 5
```

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

import { ObservableInput, OperatorFunction } from 'rxjs';
import { MonoTypeOperatorFunction, ObservableInput, OperatorFunction } from 'rxjs';
import { Result } from '../index';

@@ -13,4 +13,6 @@ export declare function resultMap<T, T2, E>(mapper: (val: T) => T2): OperatorFunction<Result<T, E>, Result<T2, E>>;

export declare function resultMergeMap<T, T2, E>(mapper: (val: T) => ObservableInput<T2>): OperatorFunction<Result<T, E>, Result<T2, E>>;
export declare function filterResultOk<T>(): OperatorFunction<Result<T, unknown>, T>;
export declare function filterResultErr<E>(): OperatorFunction<Result<unknown, E>, E>;
export declare function filterResultOk<T, E>(): OperatorFunction<Result<T, E>, T>;
export declare function filterResultErr<T, E>(): OperatorFunction<Result<T, E>, E>;
export declare function tapResultErr<T, E>(tapFn: (err: E) => void): MonoTypeOperatorFunction<Result<T, E>>;
export declare function tapResultOk<T, E>(tapFn: (val: T) => void): MonoTypeOperatorFunction<Result<T, E>>;
//# sourceMappingURL=index.d.ts.map

@@ -12,3 +12,3 @@ (function (factory) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.filterResultErr = exports.filterResultOk = exports.resultMergeMap = exports.resultSwitchMap = exports.elseMapTo = exports.elseMap = exports.resultMapErrTo = exports.resultMapTo = exports.resultMapErr = exports.resultMap = void 0;
exports.tapResultOk = exports.tapResultErr = exports.filterResultErr = exports.filterResultOk = exports.resultMergeMap = exports.resultSwitchMap = exports.elseMapTo = exports.elseMap = exports.resultMapErrTo = exports.resultMapTo = exports.resultMapErr = exports.resultMap = void 0;
var rxjs_1 = require("rxjs");

@@ -77,3 +77,3 @@ var operators_1 = require("rxjs/operators");

}), operators_1.map(function (result) {
if (result instanceof index_1.Ok || result instanceof index_1.Err) {
if (index_1.Result.isResult(result)) {
return result;

@@ -98,3 +98,3 @@ }

}), operators_1.map(function (result) {
if (result instanceof index_1.Ok || result instanceof index_1.Err) {
if (index_1.Result.isResult(result)) {
return result;

@@ -121,3 +121,23 @@ }

exports.filterResultErr = filterResultErr;
function tapResultErr(tapFn) {
return function (source) {
return source.pipe(operators_1.tap(function (r) {
if (!r.ok) {
tapFn(r.val);
}
}));
};
}
exports.tapResultErr = tapResultErr;
function tapResultOk(tapFn) {
return function (source) {
return source.pipe(operators_1.tap(function (r) {
if (r.ok) {
tapFn(r.val);
}
}));
};
}
exports.tapResultOk = tapResultOk;
});
//# sourceMappingURL=index.js.map

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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