Skip to content

Commit

Permalink
10. [release:2.0.0]
Browse files Browse the repository at this point in the history
  • Loading branch information
just-do-halee committed Oct 6, 2021
1 parent d6a0591 commit 3e2232e
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 47 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
## 2.0.0 (October 6, 2021)

### Release 2.0.0

- **_auto parsing_** `Err.eSplit(e)` do return [msg, value]: [`string`, `E | null`].
- this is kind of huge change, so i had to upgrade the major version...
- adding _unwrap_or, unwrap_or_else, unwrap_err_ on the interface of Result(=IResult)
- fixes README.md

---

## 1.4.0 (October 6, 2021)

### Release 1.4.0
Expand Down
114 changes: 90 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,24 +35,70 @@ yarn add rusultts
```ts
import { Result, Ok, Err } from 'rusultts';

// Result<T>: any type can be into it,
// This is just the generic type.

// I chose <T> as object.

type SomeType = { foo: string, bar: number };

// Also these are just some example functions.

function tryParse(token: string): Result<SomeType> {
// ... heavy stuffs
if (somethingWrong) {

// ... doing heavy stuffs ...

if (somethingWrong) { // happended

// so returns an Error-Object implementing Result<T>

return Err.new(`something wrong...`, null);

}
// ...
return Ok.new({ some: 'type', ...stuffs });

// Or returns an Ok Object containing value for <SomeType>

return Ok.new({ foo: 'any', bar: 999 });

}

function verify(token: string): boolean {
const someType = tryParse(token).unwrap(); // automatically throw
// ... more some stuffs
// tryParse() wrapping function

function verify(token: string): Result<boolean> {

// ↓ automatic throwing new Error(), or retuns the <SomeType> directly.

const someType = tryParse(token).unwrap();

// ... doing more stuffs ...

// another unwrap

const isItGood = tryGetBool(...).unwrap();

// ...
return isItGood;

return Ok.new(isItGood);
}

const bool = verify(someToken);
try {

// if unwrap is possible, you get a sign that you can use an obvious try catch statement.

const bool = verify(someToken).unwrap();

} catch(e) {

// ↓ can get [`string`, 'E | null'] type value.

const [msg, value] = Err.eSplit(e);

// message of error & contained value<E>
// this value is `null` because of Result<T> = ResultBox<T, null>

console.log(msg, value);

}
```

### ResultBox
Expand All @@ -64,33 +110,51 @@ type Result<T> = ResultBox<T, null>;
```ts
import { ResultBox, Ok, Err } from 'rusultts';

// simple example
// ResultBox<T, E>: <E> equals containing user value for Error statement. it can be any type.

function divide(a: number, b: number): ResultBox<number, number> {
if (b === 0) {
return Err.new(`b cannot be `, b);
}
return Ok.new(a / b);
}
const ok = divide(4, 2).unwrap() === 2; // true
const err = divide(4, 0); // 4 / 0

const val = divide(4, 2).unwrap(); // 4 / 2 = 2
const err = divide(4, 0); // 4 / 0, so error statement.

console.log(err.isErr); // true
const getEValue = err.unwrap_err(); // 0
const getDefault = err.unwrap_or(10); // 10
const getTrans = err.unwrap_or_else((eV: number) => eV + 1); // 1

// returns contained value<number> = 0
const getValueE = err.unwrap_err();

// if state is error, returns input value = 10
const getDefault = err.unwrap_or(10);

// like .map((x) => y) for value<E>
// ↓ will return 1
const getMapped = err.unwrap_or_else((eV: number) => eV + 1);

try {
err.unwrap();
} catch (e) {
const errMessage = Err.eSplit(e); // `b cannot be :--> 0`
const [errMessage, valueE] = Err.eSplit(e);

// print `b cannot be :--> -1` out.
console.log(errMessage, (-1 + valueE) as number);
}
```

## **Advanced**<br>

#### **./errors.ts**

```ts
import { createErrorSet } from 'rusultts';

const err = createErrorSet({
// you can easily set all errors.

export default createErrorSet({
notFound: 'not found',
somethingWrong: 'something wrong...',
wrongHeader: 'please fix your header.',
Expand All @@ -102,23 +166,25 @@ const err = createErrorSet({

```ts
import { ResultBox, Ok, Err } from 'rusultts';
// and also import our **const `err`**

function divide(a: number, b: number): ResultBox<number, number> => {
import err from './errors'; // import errors

function divide(a: number, b: number): ResultBox<number, number> {
if (b === 0) {
return err.new('dividedByZero', b); // autocompleted string
return err.new('dividedByZero', b); // autocompleted string argument
} else if (b < 0) {
return err.new('dividedByNegative', b);
}
return Ok.new(a / b);
};
}

try {
divide(4, -2).unwrap();
divide(4, -2).unwrap(); // dividedByNegative error occurs.
} catch (e) {
const val1 = err.match(e, 'dividedByZero').unwrap(); // val1 === undefined
const val2 = err.match(e, 'dividedByNegative').unwrap(); // val2 === '-2'
const val3 = err.match({ is: 'not errorType' }, 'dividedByNegative').unwrap(); // throw new Error()
// you can do error type matching.
const val1 = err.match(e, 'dividedByZero').unwrap(); // this will return undefined.
const val2 = err.match(e, 'dividedByNegative').unwrap(); // this will return value of number type, `-2`
const val3 = err.match({ is: 'not errorType' }, 'dividedByNegative').unwrap(); // throw new Error
}
```

Expand Down
7 changes: 5 additions & 2 deletions dist/rusultts.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ export interface IResult<T, E> {
readonly isOk: boolean;
readonly isErr: boolean;
unwrap(): T | never;
unwrap_or(inputValue: T): T;
unwrap_or_else(op: (innerValue: E) => T): T;
unwrap_err(): E | never;
}
/**
* ## Examples
Expand Down Expand Up @@ -122,9 +125,9 @@ export declare class Err<T, E> extends ResultBox<T, E> {
/**
*
* @param e Error | unknown
* @returns [`error.message`, `<E>.toString()`] or ***[error.message, ''] (not found)***
* @returns [`error.message`, `value<E>`] or ***[`string`, null] (not found)***
*/
static eSplit(e: Error | unknown): [string, string];
static eSplit<E>(e: Error | unknown): [string, E | null];
}
/**
* easy one, has value of Error as `null`
Expand Down
12 changes: 5 additions & 7 deletions dist/rusultts.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,17 +170,17 @@ var Err = /** @class */ (function (_super) {
/**
*
* @param e Error | unknown
* @returns [`error.message`, `<E>.toString()`] or ***[error.message, ''] (not found)***
* @returns [`error.message`, `value<E>`] or ***[`string`, null] (not found)***
*/
Err.eSplit = function (e) {
if (!(e instanceof Error)) {
return ['', ''];
return ['', null];
}
var val = e.message.split(':--> ', 2);
if (val.length !== 2) {
val = [val[0] || '', ''];
return [val[0] || '', null];
}
return val;
return [val[0], JSON.parse(val[1])];
};
return Err;
}(ResultBox));
Expand Down Expand Up @@ -231,9 +231,7 @@ var ErrSet = /** @class */ (function () {
return Err.new("e is unknown type:", e);
}
var _a = Err.eSplit(e), message = _a[0], value = _a[1];
return Ok.new(message === this.messagePair[errorMessageType]
? JSON.parse(value)
: undefined);
return Ok.new(message === this.messagePair[errorMessageType] ? value : undefined);
};
return ErrSet;
}());
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "rusultts",
"main": "dist/rusultts.js",
"types": "dist/rusultts.d.ts",
"version": "1.4.0",
"version": "2.0.0",
"description": "Rust Result Implementation for Typescript, simply. i.e. Modern error handling library.",
"author": "just-do-halee <just.do.halee@gmail.com>",
"license": "MIT",
Expand Down
17 changes: 9 additions & 8 deletions src/rusultts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ export interface IResult<T, E> {
readonly isErr: boolean;
// Returning internal value or Throw an error
unwrap(): T | never;
unwrap_or(inputValue: T): T;
unwrap_or_else(op: (innerValue: E) => T): T;
unwrap_err(): E | never;
}

/**
Expand Down Expand Up @@ -166,17 +169,17 @@ export class Err<T, E> extends ResultBox<T, E> {
/**
*
* @param e Error | unknown
* @returns [`error.message`, `<E>.toString()`] or ***[error.message, ''] (not found)***
* @returns [`error.message`, `value<E>`] or ***[`string`, null] (not found)***
*/
static eSplit(e: Error | unknown): [string, string] {
static eSplit<E>(e: Error | unknown): [string, E | null] {
if (!(e instanceof Error)) {
return ['', ''];
return ['', null];
}
let val: string[] = e.message.split(':--> ', 2);
if (val.length !== 2) {
val = [val[0] || '', ''];
return [val[0] || '', null];
}
return val as [string, string];
return [val[0], JSON.parse(val[1])];
}
}

Expand Down Expand Up @@ -254,9 +257,7 @@ export class ErrSet<M extends MessagePair> {
}
const [message, value] = Err.eSplit(e);
return Ok.new(
message === this.messagePair[errorMessageType]
? JSON.parse(value)
: undefined
message === this.messagePair[errorMessageType] ? (value as E) : undefined
);
}
}
Expand Down
10 changes: 5 additions & 5 deletions test/rusultts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,10 @@ describe('make some results', () => {
test.unwrap();
throw new Error(`testing error.`);
} catch (e) {
expect(Err.eSplit({ this: 'is unknown' })).toEqual(['', '']);
expect(Err.eSplit(new Error(``))).toEqual(['', '']);
expect(Err.eSplit(new Error(`fake Error`))[1]).toEqual('');
expect(Err.eSplit(e)[1]).toEqual(String(0));
expect(Err.eSplit({ this: 'is unknown' })).toEqual(['', null]);
expect(Err.eSplit(new Error(``))).toEqual(['', null]);
expect(Err.eSplit(new Error(`fake Error`))[1]).toEqual(null);
expect(Err.eSplit(e)[1]).toEqual(0);
}
});

Expand Down Expand Up @@ -217,7 +217,7 @@ describe('make some results', () => {
try {
res2.pop().unwrap();
} catch (e) {
expect(Err.eSplit(e)[1]).toEqual('null');
expect(Err.eSplit(e)[1]).toEqual(null);
}
stack
.push('1')
Expand Down

0 comments on commit 3e2232e

Please sign in to comment.