fp-ts
Version:
Functional programming in TypeScript
877 lines (876 loc) • 23.8 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import * as E from './Either';
import { getFilterableComposition } from './Filterable';
import { bindTo_, bind_, flow, identity, pipe } from './function';
import * as T from './Task';
// -------------------------------------------------------------------------------------
// constructors
// -------------------------------------------------------------------------------------
/**
* @category constructors
* @since 2.0.0
*/
export var left =
/*#__PURE__*/
flow(E.left, T.of);
/**
* @category constructors
* @since 2.0.0
*/
export var right =
/*#__PURE__*/
flow(E.right, T.of);
/**
* @category constructors
* @since 2.0.0
*/
export var rightTask =
/*#__PURE__*/
T.map(E.right);
/**
* @category constructors
* @since 2.0.0
*/
export var leftTask =
/*#__PURE__*/
T.map(E.left);
/**
* @category constructors
* @since 2.0.0
*/
export var rightIO =
/*#__PURE__*/
flow(T.fromIO, rightTask);
/**
* @category constructors
* @since 2.0.0
*/
export var leftIO =
/*#__PURE__*/
flow(T.fromIO, leftTask);
/**
* @category constructors
* @since 2.0.0
*/
export var fromIOEither = T.fromIO;
/**
* Derivable from `MonadThrow`.
*
* @category constructors
* @since 2.0.0
*/
export var fromEither =
/*#__PURE__*/
E.fold(left, function (a) { return right(a); });
/**
* Derivable from `MonadThrow`.
*
* @category constructors
* @since 2.0.0
*/
export var fromOption = function (onNone) { return function (ma) {
return ma._tag === 'None' ? left(onNone()) : right(ma.value);
}; };
/**
* Derivable from `MonadThrow`.
*
* @category constructors
* @since 2.0.0
*/
export var fromPredicate = function (predicate, onFalse) { return function (a) { return (predicate(a) ? right(a) : left(onFalse(a))); }; };
/**
* Transforms a `Promise` that may reject to a `Promise` that never rejects and returns an `Either` instead.
*
* Note: `f` should never `throw` errors, they are not caught.
*
* @example
* import { left, right } from 'fp-ts/Either'
* import { tryCatch } from 'fp-ts/TaskEither'
*
* tryCatch(() => Promise.resolve(1), String)().then(result => {
* assert.deepStrictEqual(result, right(1))
* })
* tryCatch(() => Promise.reject('error'), String)().then(result => {
* assert.deepStrictEqual(result, left('error'))
* })
*
* @category constructors
* @since 2.0.0
*/
export function tryCatch(f, onRejected) {
return function () { return f().then(E.right, function (reason) { return E.left(onRejected(reason)); }); };
}
// -------------------------------------------------------------------------------------
// destructors
// -------------------------------------------------------------------------------------
/**
* @category destructors
* @since 2.0.0
*/
export var fold =
/*#__PURE__*/
flow(E.fold, T.chain);
/**
* Less strict version of [`getOrElse`](#getOrElse).
*
* @category destructors
* @since 2.6.0
*/
export var getOrElseW = function (onLeft) { return function (ma) {
return pipe(ma, T.chain(E.fold(onLeft, T.of)));
}; };
/**
* @category destructors
* @since 2.0.0
*/
export var getOrElse = getOrElseW;
// -------------------------------------------------------------------------------------
// combinators
// -------------------------------------------------------------------------------------
/**
* Returns `ma` if is a `Right` or the value returned by `onLeft` otherwise.
*
* See also [alt](#alt).
*
* @example
* import * as E from 'fp-ts/Either'
* import { pipe } from 'fp-ts/function'
* import * as TE from 'fp-ts/TaskEither'
*
* async function test() {
* const errorHandler = TE.orElse((error: string) => TE.right(`recovering from ${error}...`))
* assert.deepStrictEqual(await pipe(TE.right('ok'), errorHandler)(), E.right('ok'))
* assert.deepStrictEqual(await pipe(TE.left('ko'), errorHandler)(), E.right('recovering from ko...'))
* }
*
* test()
*
* @category combinators
* @since 2.0.0
*/
export var orElse = function (f) { return T.chain(E.fold(f, right)); };
/**
* @category combinators
* @since 2.0.0
*/
export var swap =
/*#__PURE__*/
T.map(E.swap);
/**
* Less strict version of [`filterOrElse`](#filterOrElse).
*
* @since 2.9.0
*/
export var filterOrElseW = function (predicate, onFalse) {
return chainW(function (a) { return (predicate(a) ? right(a) : left(onFalse(a))); });
};
/**
* Derivable from `MonadThrow`.
*
* @category combinators
* @since 2.0.0
*/
export var filterOrElse = filterOrElseW;
/**
* Converts a function returning a `Promise` to one returning a `TaskEither`.
*
* @category combinators
* @since 2.5.0
*/
export function tryCatchK(f, onRejected) {
return function () {
var a = [];
for (var _i = 0; _i < arguments.length; _i++) {
a[_i] = arguments[_i];
}
return tryCatch(function () { return f.apply(void 0, a); }, onRejected);
};
}
/**
* @category combinators
* @since 2.4.0
*/
export function fromEitherK(f) {
return function () {
var a = [];
for (var _i = 0; _i < arguments.length; _i++) {
a[_i] = arguments[_i];
}
return fromEither(f.apply(void 0, a));
};
}
/**
* @category combinators
* @since 2.4.0
*/
export function fromIOEitherK(f) {
return function () {
var a = [];
for (var _i = 0; _i < arguments.length; _i++) {
a[_i] = arguments[_i];
}
return fromIOEither(f.apply(void 0, a));
};
}
/**
* Less strict version of [`chainEitherK`](#chainEitherK).
*
* @category combinators
* @since 2.6.1
*/
export var chainEitherKW = function (f) { return chainW(fromEitherK(f)); };
/**
* @category combinators
* @since 2.4.0
*/
export var chainEitherK = chainEitherKW;
/**
* Less strict version of [`chainIOEitherK`](#chainIOEitherK).
*
* @category combinators
* @since 2.6.1
*/
export var chainIOEitherKW = function (f) { return chainW(fromIOEitherK(f)); };
/**
* @category combinators
* @since 2.4.0
*/
export var chainIOEitherK = chainIOEitherKW;
// -------------------------------------------------------------------------------------
// non-pipeables
// -------------------------------------------------------------------------------------
var map_ = function (fa, f) { return pipe(fa, map(f)); };
/* istanbul ignore next */
var bimap_ = function (fa, f, g) { return pipe(fa, bimap(f, g)); };
/* istanbul ignore next */
var mapLeft_ = function (fa, f) { return pipe(fa, mapLeft(f)); };
var apPar_ = function (fab, fa) { return pipe(fab, ap(fa)); };
var apSeq_ = function (fab, fa) {
return pipe(fab, chain(function (f) { return pipe(fa, map(f)); }));
};
/* istanbul ignore next */
var chain_ = function (ma, f) { return pipe(ma, chain(f)); };
/* istanbul ignore next */
var alt_ = function (fa, that) { return pipe(fa, alt(that)); };
// -------------------------------------------------------------------------------------
// pipeables
// -------------------------------------------------------------------------------------
/**
* `map` can be used to turn functions `(a: A) => B` into functions `(fa: F<A>) => F<B>` whose argument and return types
* use the type constructor `F` to represent some computational context.
*
* @category Functor
* @since 2.0.0
*/
export var map = function (f) { return T.map(E.map(f)); };
/**
* Map a pair of functions over the two type arguments of the bifunctor.
*
* @category Bifunctor
* @since 2.0.0
*/
export var bimap =
/*#__PURE__*/
flow(E.bimap, T.map);
/**
* Map a function over the first type argument of a bifunctor.
*
* @category Bifunctor
* @since 2.0.0
*/
export var mapLeft = function (f) {
return T.map(E.mapLeft(f));
};
/**
* Less strict version of [`ap`](#ap).
*
* @category Apply
* @since 2.8.0
*/
export var apW = function (fa) {
return flow(T.map(function (gab) { return function (ga) { return E.apW(ga)(gab); }; }), T.ap(fa));
};
/**
* Apply a function to an argument under a type constructor.
*
* @category Apply
* @since 2.0.0
*/
export var ap = apW;
/**
* Combine two effectful actions, keeping only the result of the first.
*
* Derivable from `Apply`.
*
* @category combinators
* @since 2.0.0
*/
export var apFirst = function (fb) {
return flow(map(function (a) { return function () { return a; }; }), ap(fb));
};
/**
* Combine two effectful actions, keeping only the result of the second.
*
* Derivable from `Apply`.
*
* @category combinators
* @since 2.0.0
*/
export var apSecond = function (fb) {
return flow(map(function () { return function (b) { return b; }; }), ap(fb));
};
/**
* Less strict version of [`chain`](#chain).
*
* @category Monad
* @since 2.6.0
*/
export var chainW = function (f) { return function (ma) {
return pipe(ma, T.chain(E.fold(left, f)));
}; };
/**
* Composes computations in sequence, using the return value of one computation to determine the next computation.
*
* @category Monad
* @since 2.0.0
*/
export var chain = chainW;
/**
* Less strict version of [`chainFirst`](#chainFirst).
*
* Derivable from `Monad`.
*
* @category combinators
* @since 2.8.0
*/
export var chainFirstW = function (f) {
return chainW(function (a) {
return pipe(f(a), map(function () { return a; }));
});
};
/**
* Composes computations in sequence, using the return value of one computation to determine the next computation and
* keeping only the result of the first.
*
* Derivable from `Monad`.
*
* @category combinators
* @since 2.0.0
*/
export var chainFirst = chainFirstW;
/**
* Derivable from `Monad`.
*
* @category combinators
* @since 2.0.0
*/
export var flatten =
/*#__PURE__*/
chain(identity);
/**
* Less strict version of [`alt`](#alt).
*
* @category Alt
* @since 2.9.0
*/
export var altW = function (that) { return function (fa) { return pipe(fa, T.chain(E.fold(that, right))); }; };
/**
* Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to
* types of kind `* -> *`.
*
* In case of `TaskEither` returns `fa` if is a `Right` or the value returned by `that` otherwise.
*
* See also [orElse](#orElse).
*
* @example
* import * as E from 'fp-ts/Either'
* import { pipe } from 'fp-ts/function'
* import * as TE from 'fp-ts/TaskEither'
*
* async function test() {
* assert.deepStrictEqual(
* await pipe(
* TE.right(1),
* TE.alt(() => TE.right(2))
* )(),
* E.right(1)
* )
* assert.deepStrictEqual(
* await pipe(
* TE.left('a'),
* TE.alt(() => TE.right(2))
* )(),
* E.right(2)
* )
* assert.deepStrictEqual(
* await pipe(
* TE.left('a'),
* TE.alt(() => TE.left('b'))
* )(),
* E.left('b')
* )
* }
*
* test()
*
* @category Alt
* @since 2.0.0
*/
export var alt = altW;
/**
* Wrap a value into the type constructor.
*
* Equivalent to [`right`](#right).
*
* @category Applicative
* @since 2.0.0
*/
export var of = right;
/**
* @category MonadIO
* @since 2.7.0
*/
export var fromIO = rightIO;
/**
* @category MonadTask
* @since 2.7.0
*/
export var fromTask = rightTask;
/**
* @category MonadTask
* @since 2.7.0
*/
export var throwError = left;
// -------------------------------------------------------------------------------------
// instances
// -------------------------------------------------------------------------------------
/**
* @category instances
* @since 2.0.0
*/
export var URI = 'TaskEither';
/**
* Semigroup returning the left-most non-`Left` value. If both operands are `Right`s then the inner values are
* concatenated using the provided `Semigroup`
*
* @category instances
* @since 2.0.0
*/
export function getSemigroup(S) {
return T.getSemigroup(E.getSemigroup(S));
}
/**
* Semigroup returning the left-most `Left` value. If both operands are `Right`s then the inner values
* are concatenated using the provided `Semigroup`
*
* @category instances
* @since 2.0.0
*/
export function getApplySemigroup(S) {
return T.getSemigroup(E.getApplySemigroup(S));
}
/**
* @category instances
* @since 2.0.0
*/
export function getApplyMonoid(M) {
return {
concat: getApplySemigroup(M).concat,
empty: right(M.empty)
};
}
/**
* @category instances
* @since 2.7.0
*/
export function getApplicativeTaskValidation(A, SE) {
var AV = E.getApplicativeValidation(SE);
var ap = function (fga) { return function (fgab) {
return A.ap(A.map(fgab, function (h) { return function (ga) { return AV.ap(h, ga); }; }), fga);
}; };
return {
URI: URI,
_E: undefined,
map: map_,
ap: function (fab, fa) { return pipe(fab, ap(fa)); },
of: of
};
}
/**
* @category instances
* @since 2.7.0
*/
export function getAltTaskValidation(SE) {
return {
URI: URI,
_E: undefined,
map: map_,
alt: function (me, that) {
return pipe(me, T.chain(function (e1) {
return E.isRight(e1)
? T.of(e1)
: pipe(that(), T.map(function (e2) { return (E.isLeft(e2) ? E.left(SE.concat(e1.left, e2.left)) : e2); }));
}));
}
};
}
// TODO: remove in v3
/**
* @category instances
* @since 2.0.0
*/
export function getTaskValidation(SE) {
var applicativeTaskValidation = getApplicativeTaskValidation(T.ApplicativePar, SE);
var altTaskValidation = getAltTaskValidation(SE);
return {
URI: URI,
_E: undefined,
map: map_,
ap: applicativeTaskValidation.ap,
of: of,
chain: chain_,
bimap: bimap_,
mapLeft: mapLeft_,
alt: altTaskValidation.alt,
fromIO: fromIO,
fromTask: fromTask,
throwError: throwError
};
}
/**
* @category instances
* @since 2.1.0
*/
export function getFilterable(M) {
var W = E.getWitherable(M);
var F = getFilterableComposition(T.Monad, W);
return {
URI: URI,
_E: undefined,
map: map_,
compact: F.compact,
separate: F.separate,
filter: F.filter,
filterMap: F.filterMap,
partition: F.partition,
partitionMap: F.partitionMap
};
}
/**
* @category instances
* @since 2.7.0
*/
export var Functor = {
URI: URI,
map: map_
};
/**
* @category instances
* @since 2.7.0
*/
export var ApplicativePar = {
URI: URI,
map: map_,
ap: apPar_,
of: of
};
/**
* @category instances
* @since 2.7.0
*/
export var ApplicativeSeq = {
URI: URI,
map: map_,
ap: apSeq_,
of: of
};
/**
* @category instances
* @since 2.7.0
*/
export var Bifunctor = {
URI: URI,
bimap: bimap_,
mapLeft: mapLeft_
};
/**
* @category instances
* @since 2.7.0
*/
export var Alt = {
URI: URI,
map: map_,
alt: alt_
};
// TODO: remove in v3
/**
* @category instances
* @since 2.0.0
*/
export var taskEither = {
URI: URI,
bimap: bimap_,
mapLeft: mapLeft_,
map: map_,
of: of,
ap: apPar_,
chain: chain_,
alt: alt_,
fromIO: fromIO,
fromTask: fromTask,
throwError: throwError
};
// TODO: remove in v3
/**
* Like `TaskEither` but `ap` is sequential
*
* @category instances
* @since 2.0.0
*/
export var taskEitherSeq = {
URI: URI,
bimap: bimap_,
mapLeft: mapLeft_,
map: map_,
of: of,
ap: apSeq_,
chain: chain_,
alt: alt_,
fromIO: fromIO,
fromTask: fromTask,
throwError: throwError
};
export function taskify(f) {
return function () {
var args = Array.prototype.slice.call(arguments);
return function () {
return new Promise(function (resolve) {
var cbResolver = function (e, r) { return (e != null ? resolve(E.left(e)) : resolve(E.right(r))); };
f.apply(null, args.concat(cbResolver));
});
};
};
}
/**
* Make sure that a resource is cleaned up in the event of an exception (\*). The release action is called regardless of
* whether the body action throws (\*) or returns.
*
* (\*) i.e. returns a `Left`
*
* Derivable from `MonadThrow`.
*
* @since 2.0.0
*/
export var bracket = function (acquire, use, release) {
return pipe(acquire, chain(function (a) {
return pipe(pipe(use(a), T.map(E.right)), chain(function (e) {
return pipe(release(a, e), chain(function () { return (E.isLeft(e) ? left(e.left) : of(e.right)); }));
}));
}));
};
// -------------------------------------------------------------------------------------
// do notation
// -------------------------------------------------------------------------------------
/**
* @since 2.9.0
*/
export var Do =
/*#__PURE__*/
of({});
/**
* @since 2.8.0
*/
export var bindTo = function (name) {
return map(bindTo_(name));
};
/**
* @since 2.8.0
*/
export var bindW = function (name, f) {
return chainW(function (a) {
return pipe(f(a), map(function (b) { return bind_(a, name, b); }));
});
};
/**
* @since 2.8.0
*/
export var bind = bindW;
// -------------------------------------------------------------------------------------
// pipeable sequence S
// -------------------------------------------------------------------------------------
/**
* @since 2.8.0
*/
export var apSW = function (name, fb) {
return flow(map(function (a) { return function (b) { return bind_(a, name, b); }; }), apW(fb));
};
/**
* @since 2.8.0
*/
export var apS = apSW;
// -------------------------------------------------------------------------------------
// array utils
// -------------------------------------------------------------------------------------
/**
* @since 2.9.0
*/
export var traverseArrayWithIndex = function (f) { return function (arr) {
return pipe(arr, T.traverseArrayWithIndex(f), T.map(E.sequenceArray));
}; };
/**
* this function has the same behavior of `A.traverse(TE.taskEither)` but it's stack safe and performs better
*
* *this function run all tasks in parallel and does not bail out, for sequential version use `traverseSeqArray`*
*
* @example
*
* import * as TE from 'fp-ts/TaskEither'
* import * as A from 'fp-ts/Array'
* import { right } from 'fp-ts/Either'
* import { pipe } from 'fp-ts/function'
*
* const PostRepo = {
* findById : (id: number) => TE.of({id, title: ''})
* }
*
* const findAllPosts = (ids:number[]) => pipe(ids, TE.traverseArray(PostRepo.findById))
*
* async function test() {
* const ids = A.range(0, 10)
*
* assert.deepStrictEqual(
* await findAllPosts(ids)(),
* right(
* pipe(
* ids,
* A.map((id) => ({ id, title: ''}))
* )
* )
* )
* }
*
* test()
*
* @since 2.9.0
*/
export var traverseArray = function (f) { return traverseArrayWithIndex(function (_, a) { return f(a); }); };
/**
* this function has the same behavior of `A.sequence(TE.taskEither)` but it's stack safe and performs better
*
* *this function run all tasks in parallel and does not bail out, for sequential version use `sequenceSeqArray`*
*
* @example
*
* import * as TE from 'fp-ts/TaskEither'
* import * as A from 'fp-ts/Array'
* import { right } from 'fp-ts/Either'
* import { pipe } from 'fp-ts/function'
*
* const PostRepo = {
* findById : (id: number) => TE.of({id, title: ''})
* }
*
* const findAllPosts = (ids:number[]) => pipe(ids, A.map(PostRepo.findById), TE.sequenceArray)
*
* async function test() {
* const ids = A.range(0, 10)
*
* assert.deepStrictEqual(
* await findAllPosts(ids)(),
* right(
* pipe(
* ids,
* A.map((id) => ({ id, title: ''}))
* )
* )
* )
* }
*
* test()
*
* @since 2.9.0
*/
export var sequenceArray =
/*#__PURE__*/
traverseArray(identity);
/**
* @since 2.9.0
*/
export var traverseSeqArrayWithIndex = function (f) { return function (arr) { return function () { return __awaiter(void 0, void 0, void 0, function () {
var result, i, e;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
result = [];
i = 0;
_a.label = 1;
case 1:
if (!(i < arr.length)) return [3 /*break*/, 4];
return [4 /*yield*/, f(i, arr[i])()];
case 2:
e = _a.sent();
if (E.isLeft(e)) {
return [2 /*return*/, e];
}
result.push(e.right);
_a.label = 3;
case 3:
i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, E.right(result)];
}
});
}); }; }; };
/**
* this function has the same behavior of `A.traverse(TE.taskEitherSeq)` but it's stack safe and performs better
*
* *this function run all tasks in sequential order and bails out on left side of either, for parallel version use `traverseArray`*
*
* @since 2.9.0
*/
export var traverseSeqArray = function (f) { return traverseSeqArrayWithIndex(function (_, a) { return f(a); }); };
/**
* this function has the same behavior of `A.sequence(TE.taskEitherSeq)` but it's stack safe and performs better
*
* *this function run all tasks in sequential order and bails out on left side of either, for parallel version use `sequenceArray`*
*
* @since 2.9.0
*/
export var sequenceSeqArray =
/*#__PURE__*/
traverseSeqArray(identity);