Skip to content

Commit

Permalink
Merge pull request #2 from RobDWaller/0.3.0
Browse files Browse the repository at this point in the history
0.3.0
  • Loading branch information
RobDWaller authored Jun 26, 2020
2 parents 7808c3e + 87f5694 commit f544a80
Show file tree
Hide file tree
Showing 13 changed files with 383 additions and 214 deletions.
40 changes: 20 additions & 20 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
MIT License
Copyright (c) 2020 Rob Waller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
MIT License

Copyright (c) 2020 Rob Waller

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
256 changes: 142 additions & 114 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,115 +1,143 @@
[![Actions Status](https://github.com/robdwaller/resulty/workflows/ci/badge.svg)](https://github.com/robdwaller/resulty/actions)

# Resulty

Provides simple, Rust-like [Result](https://doc.rust-lang.org/std/result/enum.Result.html) and [Option](https://doc.rust-lang.org/std/option/enum.Option.html) objects for Deno. This provides an alternate approach to handling errors and mixed return types.

Instead of throwing exceptions everywhere you can easily bubble up errors by returning a `Result` type which is either an instance of `Ok` or `Err`.

The Option objects allow you to return a standard type where the result of a method maybe something or nothing.

## Setup

To add Resulty to your project simply import the `ok()`, `err()`, `some()` and `none()` methods along with the `Result<T>` and `Opt<T>` types from the Deno Land module.

```js
import { ok, err, some, none, Result, Opt } from "https://deno.land/x/resulty/mod.ts"
```

## Usage

The core of the this library are the `ok()`, `err()`, `some()` and `none()` methods. The `ok()` and `err()` methods return an instance of `Result<T>`, and the `some()` and `none()` methods return an instance of `Opt<T>`.

Both `Result<T>` and `Opt<T>` are wrappers for other types and objects. And you can access these contained types and objects via the `unwrap()` method.

```js
import { Result, ok } from "https://deno.land/x/resulty/mod.ts";

const isOk: Result<string> = ok("Hello");

console.log(isOk.unwrap());
// Hello
```

One difference between `Result<T>` and `Opt<T>` objects is `Result<T>` objects have two additional methods to `unwrap()`, which are `isOk()` and `isError()`. These methods allow you to quickly confirm whether the object you have received represents a success or failure scenario.

### Result

Result objects, AKA `Result<T>` objects, can be generated by either the `ok()` or `err()` methods. The former represents a successful outcome the latter a failure.

Result objects contain three methods, `unwrap()`, `isOk()` and `isError()`.

In this example the code returns a `Result<string>`. As you see both the `ok()` and `err()` methods receive a string.
```js
import { Result, ok, err } from "https://deno.land/x/resulty/mod.ts";

const isSandra = function (name: string): Result<string> {
if (name === "Sandra") {
return ok("Is Sandra");
}
return err("Is not Sandra");
};

const geoff = isSandra("Geoff");
console.log(geoff.unwrap());
// "Is not Sandra"

const sandra = isSandra("Sandra");

console.log(sandra.unwrap());
// "Is Sandra"
```

A more advanced use case may involve a situation where the `ok()` method receives a number and the `err()` method receives a string. In this scenario you can reference a union type in the `Result<number | string>` return type.

```js
import { Result, ok, err } from "https://deno.land/x/resulty/mod.ts";

const findNumber = function (toFind: number): Result<number | string> {
let numbers = [1, 4, 6, 7, 21, 33];

if (numbers.includes(toFind)) {
return ok(toFind);
}
return err(`Number: ${toFind} could not be found.`);
};

const found = findNumber(6);
console.log(found.unwrap());
// 6

const notFound = findNumber(9);
console.log(notFound.unwrap())
// Number: 9 could not be found.
```

### Option

Option objects, AKA `Opt<T>` obejects, can be generated via the `some()` or `none()` methods. The `Opt<T>` object only include a single method `unwrap()`.

Options are useful in scenarios where a system failure hasn't occurred but either something or nothing can be returned. For instance when looking for a record in a data store of some kind.
```js
import { Opt, some, none } from "https://deno.land/x/resulty/mod.ts";

let findRecord = function (id: number): Opt<string> {
let records = [{id: 1, value: "Hello"}, {id: 13, value: "World"}];

records = records.filter((item) => {
return item.id === id;
});

if (records.length === 1) {
return some(records[0].value);
}

return none();
};

const found = findRecord(13);
console.log(found.unwrap());
// "World"

const notFound = findRecord(2);
console.log(notFound.unwrap());
// null
[![Actions Status](https://github.com/robdwaller/resulty/workflows/ci/badge.svg)](https://github.com/robdwaller/resulty/actions) ![GitHub release (latest by date)](https://img.shields.io/github/v/release/robdwaller/resulty) ![GitHub](https://img.shields.io/github/license/robdwaller/resulty) [![deno doc](https://doc.deno.land/badge.svg)](https://doc.deno.land/https/deno.land/x/resulty/mod.ts)

# Resulty

Provides simple, Rust-like [Result](https://doc.rust-lang.org/std/result/enum.Result.html) and [Option](https://doc.rust-lang.org/std/option/enum.Option.html) objects for Deno. This provides an alternate approach to handling errors and mixed return types.

Instead of throwing exceptions everywhere you can easily bubble up errors by returning a `Result` type which is either an instance of `Ok` or `Err`.

The Option objects allow you to return a standard type where the result of a method maybe something or nothing.

## Installation / Setup

To add Resulty to your project simply import the `ok()`, `err()`, `some()` and `none()` methods along with the `Result<T>` and `Opt<T>` types from `https://deno.land/x/resulty@0.3.0/mod.ts`.

```js
import {
ok,
err,
some,
none,
Result,
Opt,
Panic,
} from "https://deno.land/x/resulty@0.3.0/mod.ts"
```

## Usage

The core functionality of the this library is contained in the `ok()`, `err()`, `some()` and `none()` methods. The `ok()` and `err()` methods return an instance of `Result<T>`, and the `some()` and `none()` methods return an instance of `Opt<T>`.

Both `Result<T>` and `Opt<T>` are wrappers for other types and objects. And you can access these contained types and objects via the `unwrap()` method.

```js
import { Result, ok } from "https://deno.land/x/resulty@0.3.0/mod.ts";

const isOk: Result<string> = ok("Hello");

console.log(isOk.unwrap());
// Hello
```

### Unwrap vs Unwrap Err and Unwrap None

Both Result and Option objects make an `unwrap()` method available which will return what is contained within the Result or Option object.

If the `unwrap()` method is called on an `Err` or `None` object it will `Panic`. If you need to retrieve what is contained in the `Err` object use the method `unwrapErr()`.

An instance of `None` will not contain anything, but in certain instances you may wish to unwrap a `None` without panicking, you can do this by calling `unwrapNone()`.

### Result

Result objects can be generated by either the `ok()` or `err()` methods. The former represents a successful outcome the latter a failure.

Available `Result<T>` methods:

- `unwrap(): T | void;`
- `unwrapErr(): T | void;`
- `isOk(): boolean;`
- `isErr(): boolean;`

In this example the code returns a `Result<string>`. As you can see both the `ok()` and `err()` methods receive a string.

```js
import { Result, ok, err } from "https://deno.land/x/resulty@0.3.0/mod.ts";

const isSandra = function (name: string): Result<string> {
if (name === "Sandra") {
return ok("Is Sandra");
}
return err("Is not Sandra");
};

const geoff = isSandra("Geoff");
console.log(geoff.unwrapErr());
// "Is not Sandra"

const sandra = isSandra("Sandra");

console.log(sandra.unwrap());
// "Is Sandra"
```

A more advanced use case may involve a situation where the `ok()` method receives a number and the `err()` method receives a string. In this scenario you can reference a union type in the `Result<number | string>` return type.

```js
import { Result, ok, err } from "https://deno.land/x/resulty@0.3.0/mod.ts";

const findNumber = function (toFind: number): Result<number | string> {
const numbers = [1, 4, 6, 7, 21, 33];

if (numbers.includes(toFind)) {
return ok(toFind);
}
return err(`Number: ${toFind} could not be found.`);
};

const found = findNumber(6);
console.log(found.unwrap());
// 6

const notFound = findNumber(9);
console.log(notFound.unwrapErr())
// Number: 9 could not be found.
```

### Option

Option objects can be generated via the `some()` or `none()` methods.

Available `Opt<T>` methods:

- `unwrap(): T | void;`
- `unwrapNone(): T | void;`
- `isSome(): boolean;`
- `isNone(): boolean;`

Options are useful in scenarios where a system failure hasn't occurred but either something or nothing can be returned. For instance when looking for a record in a data store of some kind.

```js
import { Opt, some, none } from "https://deno.land/x/resulty@0.3.0/mod.ts";

let findRecord = function (id: number): Opt<string> {
let records = [{id: 1, value: "Hello"}, {id: 13, value: "World"}];

records = records.filter((item) => {
return item.id === id;
});

if (records.length === 1) {
return some(records[0].value);
}

return none();
};

const found = findRecord(13);
console.log(found.unwrap());
// "World"

const notFound = findRecord(2);
console.log(notFound.unwrapNone());
// undefined
```
4 changes: 4 additions & 0 deletions dev_deps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export {
assertStrictEq,
assertThrows,
} from "https://deno.land/std@0.56.0/testing/asserts.ts";
14 changes: 14 additions & 0 deletions egg.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "resulty",
"description": "Provides simple, Rust-like Result and Option objects for Deno.",
"version": "0.3.0",
"entry": "./mod.ts",
"stable": false,
"repository": "https://github.com/robdwaller/resulty",
"files": [
"./mod.ts",
"./src/**/*",
"./README.md",
"./LICENSE.md"
]
}
2 changes: 2 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Result, Ok, Err } from "./src/result.ts";
import { Opt, None, Some } from "./src/option.ts";
export { Panic } from "./src/panic.ts";

export function some<T>(something: T): Opt<T> {
return new Some<T>(something);
Expand All @@ -8,6 +9,7 @@ export function some<T>(something: T): Opt<T> {
export function none(): Opt<null> {
return new None();
}

export function ok<T>(result: T): Result<T> {
return new Ok<T>(result);
}
Expand Down
3 changes: 3 additions & 0 deletions src/is.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
interface Is {
(): boolean;
}
35 changes: 32 additions & 3 deletions src/option.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { Unwrap } from "./unwrap.ts";
import { Is } from "./is.ts";
import { Panic } from "./panic.ts";

export type Opt<T> = Some<T> | None;

interface Options<T> {
readonly option: T | null;
readonly unwrap: Unwrap<T>;
unwrap: Unwrap<T>;
unwrapNone: Unwrap<T>;
isSome: Is;
isNone: Is;
}

export class Some<T> implements Options<T> {
Expand All @@ -17,12 +22,36 @@ export class Some<T> implements Options<T> {
unwrap(): T {
return this.option;
}

unwrapNone(): void {
throw new Panic(String(this.option));
}

isSome(): boolean {
return true;
}

isNone(): boolean {
return false;
}
}

export class None implements Options<null> {
readonly option = null;

unwrap(): null {
return this.option;
unwrap(): void {
throw new Panic("Cannot unwrap None.");
}

unwrapNone(): void {
// Return nothing
}

isSome(): boolean {
return false;
}

isNone(): boolean {
return true;
}
}
Loading

0 comments on commit f544a80

Please sign in to comment.