Skip to content

Commit

Permalink
feat(Contract): add mapResult method
Browse files Browse the repository at this point in the history
  • Loading branch information
bigslycat committed Apr 10, 2019
1 parent efde9ef commit ebf95ed
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,5 +195,19 @@ Aliases: `isUndefined`, `passUndefined`, `isUndef`, `passUndef`, `isVoid`, `pass
Creates a contract which expects `undefined`.
## Using with ADT
```js
import * as t from 'typed-contracts';
import { type Either, Right, Left } from 'igogo';

const transform = <T>(
result: t.ValidationError | T,
): Either<t.ValidationError, T> =>
result instanceof t.ValidationError ? Left(result) : Right(result);

const string = t.string.mapResult(transform);
```
[status-url]: https://travis-ci.org/bigslycat/typed-contracts
[status-img]: https://travis-ci.org/bigslycat/typed-contracts.svg?branch=master
9 changes: 9 additions & 0 deletions src/Contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ export type Contract<+T> = {
...$ReadOnlyArray<void>
): (value: mixed) => ValidationError | ?T,
maybe(valueName: string, value: mixed): ValidationError | ?T,

mapResult<M>(
transform: (result: ValidationError | T) => M,
): ((valueName: string, ...$ReadOnlyArray<void>) => (value: mixed) => M) &
((valueName: string, value: mixed) => M),
};

declare function curry2<A, B, C>(
Expand Down Expand Up @@ -61,8 +66,12 @@ export function of(validate) {
return result;
};

const mapResult = transform =>
curry2((valueName, value) => transform(validate(valueName, value)));

contract.maybe = maybe;
contract.optional = optional;
contract.mapResult = mapResult;

return contract;
}
5 changes: 5 additions & 0 deletions src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ export type Contract<T> = {
valueName: string
): (value: unknown) => ValidationError | void | null | T,
maybe(valueName: string, value: unknown): ValidationError | void | null | T,

mapResult<M>(
transform: (result: ValidationError | T) => M,
): ((valueName: string) => (value: unknown) => M) &
((valueName: string, value: unknown) => M),
};

export declare function of<T>(
Expand Down

0 comments on commit ebf95ed

Please sign in to comment.