mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-02 03:15:52 +08:00
remove Either module (#114)
This commit is contained in:
@@ -4,7 +4,6 @@
|
||||
* @since 2.0.0
|
||||
*/
|
||||
|
||||
import * as Either from "./Either.js"
|
||||
import * as Equal from "./Equal.js"
|
||||
import * as Equivalence from "./Equivalence.js"
|
||||
import type { LazyArg } from "./Function.js"
|
||||
@@ -17,6 +16,7 @@ import * as Option from "./Option.js"
|
||||
import * as Order from "./Order.js"
|
||||
import * as Predicate from "./Predicate.js"
|
||||
import * as Record from "./Record.js"
|
||||
import * as Result from "./Result.js"
|
||||
import * as Tuple from "./Tuple.js"
|
||||
import type { NoInfer } from "./Types.js"
|
||||
|
||||
@@ -2502,12 +2502,12 @@ export const filterMapWhile: {
|
||||
* **Example**
|
||||
*
|
||||
* ```ts
|
||||
* import { Array, Either } from "effect";
|
||||
* import { Array, Result } from "effect";
|
||||
*
|
||||
* const isEven = (x: number) => x % 2 === 0
|
||||
*
|
||||
* const result = Array.partitionMap([1, 2, 3, 4, 5], x =>
|
||||
* isEven(x) ? Either.right(x) : Either.left(x)
|
||||
* isEven(x) ? Result.ok(x) : Result.err(x)
|
||||
* )
|
||||
* console.log(result)
|
||||
* // [
|
||||
@@ -2520,20 +2520,20 @@ export const filterMapWhile: {
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const partitionMap: {
|
||||
<A, B, C>(f: (a: A, i: number) => Either.Either<C, B>): (self: Iterable<A>) => [left: Array<B>, right: Array<C>]
|
||||
<A, B, C>(self: Iterable<A>, f: (a: A, i: number) => Either.Either<C, B>): [left: Array<B>, right: Array<C>]
|
||||
<A, B, C>(f: (a: A, i: number) => Result.Result<C, B>): (self: Iterable<A>) => [left: Array<B>, right: Array<C>]
|
||||
<A, B, C>(self: Iterable<A>, f: (a: A, i: number) => Result.Result<C, B>): [left: Array<B>, right: Array<C>]
|
||||
} = dual(
|
||||
2,
|
||||
<A, B, C>(self: Iterable<A>, f: (a: A, i: number) => Either.Either<C, B>): [left: Array<B>, right: Array<C>] => {
|
||||
<A, B, C>(self: Iterable<A>, f: (a: A, i: number) => Result.Result<C, B>): [left: Array<B>, right: Array<C>] => {
|
||||
const left: Array<B> = []
|
||||
const right: Array<C> = []
|
||||
const as = fromIterable(self)
|
||||
for (let i = 0; i < as.length; i++) {
|
||||
const e = f(as[i], i)
|
||||
if (Either.isLeft(e)) {
|
||||
left.push(e.left)
|
||||
if (Result.isErr(e)) {
|
||||
left.push(e.err)
|
||||
} else {
|
||||
right.push(e.right)
|
||||
right.push(e.ok)
|
||||
}
|
||||
}
|
||||
return [left, right]
|
||||
@@ -2561,27 +2561,27 @@ export const getSomes: <T extends Iterable<Option.Option<X>>, X = any>(
|
||||
) => Array<Option.Option.Value<ReadonlyArray.Infer<T>>> = filterMap(identity as any)
|
||||
|
||||
/**
|
||||
* Retrieves the `Left` values from an `Iterable` of `Either`s, collecting them into an array.
|
||||
* Retrieves the `Err` values from an `Iterable` of `Result`s, collecting them into an array.
|
||||
*
|
||||
* **Example**
|
||||
*
|
||||
* ```ts
|
||||
* import { Array, Either } from "effect"
|
||||
* import { Array, Result } from "effect"
|
||||
*
|
||||
* const result = Array.getLefts([Either.right(1), Either.left("err"), Either.right(2)])
|
||||
* const result = Array.getErrs([Result.ok(1), Result.err("err"), Result.ok(2)])
|
||||
* console.log(result) // ["err"]
|
||||
* ```
|
||||
*
|
||||
* @category filtering
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const getLefts = <T extends Iterable<Either.Either<any, any>>>(
|
||||
export const getErrs = <T extends Iterable<Result.Result<any, any>>>(
|
||||
self: T
|
||||
): Array<Either.Either.Left<ReadonlyArray.Infer<T>>> => {
|
||||
): Array<Result.Result.Err<ReadonlyArray.Infer<T>>> => {
|
||||
const out: Array<any> = []
|
||||
for (const a of self) {
|
||||
if (Either.isLeft(a)) {
|
||||
out.push(a.left)
|
||||
if (Result.isErr(a)) {
|
||||
out.push(a.err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2589,27 +2589,27 @@ export const getLefts = <T extends Iterable<Either.Either<any, any>>>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the `Right` values from an `Iterable` of `Either`s, collecting them into an array.
|
||||
* Retrieves the `Ok` values from an `Iterable` of `Result`s, collecting them into an array.
|
||||
*
|
||||
* **Example**
|
||||
*
|
||||
* ```ts
|
||||
* import { Array, Either } from "effect"
|
||||
* import { Array, Result } from "effect"
|
||||
*
|
||||
* const result = Array.getRights([Either.right(1), Either.left("err"), Either.right(2)])
|
||||
* const result = Array.getOks([Result.ok(1), Result.err("err"), Result.ok(2)])
|
||||
* console.log(result) // [1, 2]
|
||||
* ```
|
||||
*
|
||||
* @category filtering
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const getRights = <T extends Iterable<Either.Either<any, any>>>(
|
||||
export const getOks = <T extends Iterable<Result.Result<any, any>>>(
|
||||
self: T
|
||||
): Array<Either.Either.Right<ReadonlyArray.Infer<T>>> => {
|
||||
): Array<Result.Result.Ok<ReadonlyArray.Infer<T>>> => {
|
||||
const out: Array<any> = []
|
||||
for (const a of self) {
|
||||
if (Either.isRight(a)) {
|
||||
out.push(a.right)
|
||||
if (Result.isOk(a)) {
|
||||
out.push(a.ok)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2689,10 +2689,11 @@ export const partition: {
|
||||
* @category filtering
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const separate: <T extends Iterable<Either.Either<any, any>>>(
|
||||
export const separate: <T extends Iterable<Result.Result<any, any>>>(
|
||||
self: T
|
||||
) => [Array<Either.Either.Left<ReadonlyArray.Infer<T>>>, Array<Either.Either.Right<ReadonlyArray.Infer<T>>>] =
|
||||
partitionMap(identity)
|
||||
) => [Array<Result.Result.Err<ReadonlyArray.Infer<T>>>, Array<Result.Result.Ok<ReadonlyArray.Infer<T>>>] = partitionMap(
|
||||
identity
|
||||
)
|
||||
|
||||
/**
|
||||
* Reduces an array from the left.
|
||||
@@ -2818,19 +2819,19 @@ export const flatMapNullable: {
|
||||
)
|
||||
|
||||
/**
|
||||
* Lifts a function that returns an `Either` into a function that returns an array.
|
||||
* If the `Either` is a left, it returns an empty array.
|
||||
* If the `Either` is a right, it returns an array with the right value.
|
||||
* Lifts a function that returns an `Result` into a function that returns an array.
|
||||
* If the `Result` is an `Err`, it returns an empty array.
|
||||
* If the `Result` is an `Ok`, it returns an array with the Ok value.
|
||||
*
|
||||
* **Example**
|
||||
*
|
||||
* ```ts
|
||||
* import { Array, Either } from "effect"
|
||||
* import { Array, Result } from "effect"
|
||||
*
|
||||
* const parseNumber = (s: string): Either.Either<number, Error> =>
|
||||
* isNaN(Number(s)) ? Either.left(new Error("Not a number")) : Either.right(Number(s))
|
||||
* const parseNumber = (s: string): Result.Result<number, Error> =>
|
||||
* isNaN(Number(s)) ? Result.err(new Error("Not a number")) : Result.ok(Number(s))
|
||||
*
|
||||
* const liftedParseNumber = Array.liftEither(parseNumber)
|
||||
* const liftedParseNumber = Array.liftResult(parseNumber)
|
||||
*
|
||||
* const result1 = liftedParseNumber("42")
|
||||
* console.log(result1) // [42]
|
||||
@@ -2840,19 +2841,19 @@ export const flatMapNullable: {
|
||||
*
|
||||
* // Explanation:
|
||||
* // The function parseNumber is lifted to return an array.
|
||||
* // When parsing "42", it returns an Either.left with the number 42, resulting in [42].
|
||||
* // When parsing "not a number", it returns an Either.right with an error, resulting in an empty array [].
|
||||
* // When parsing "42", it returns an Result.err with the number 42, resulting in [42].
|
||||
* // When parsing "not a number", it returns an Result.ok with an error, resulting in an empty array [].
|
||||
* ```
|
||||
*
|
||||
* @category lifting
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const liftEither = <A extends Array<unknown>, E, B>(
|
||||
f: (...a: A) => Either.Either<B, E>
|
||||
export const liftResult = <A extends Array<unknown>, E, B>(
|
||||
f: (...a: A) => Result.Result<B, E>
|
||||
) =>
|
||||
(...a: A): Array<B> => {
|
||||
const e = f(...a)
|
||||
return Either.isLeft(e) ? [] : [e.right]
|
||||
return Result.isErr(e) ? [] : [e.ok]
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
* @since 2.0.0
|
||||
*/
|
||||
import * as Arr from "./Array.js"
|
||||
import * as Either from "./Either.js"
|
||||
import { identity } from "./Function.js"
|
||||
import * as Option from "./Option.js"
|
||||
import type { Predicate } from "./Predicate.js"
|
||||
import * as Result from "./Result.js"
|
||||
import type * as Types from "./Types.js"
|
||||
|
||||
/**
|
||||
@@ -99,10 +99,10 @@ export declare namespace Brand {
|
||||
*/
|
||||
option(args: Brand.Unbranded<A>): Option.Option<A>
|
||||
/**
|
||||
* Constructs a branded type from a value of type `A`, returning `Right<A>`
|
||||
* if the provided `A` is valid, `Left<BrandError>` otherwise.
|
||||
* Constructs a branded type from a value of type `A`, returning `Ok<A>`
|
||||
* if the provided `A` is valid, `Err<BrandError>` otherwise.
|
||||
*/
|
||||
either(args: Brand.Unbranded<A>): Either.Either<A, Brand.BrandErrors>
|
||||
result(args: Brand.Unbranded<A>): Result.Result<A, Brand.BrandErrors>
|
||||
/**
|
||||
* Attempts to refine the provided value of type `A`, returning `true` if
|
||||
* the provided `A` is valid, `false` otherwise.
|
||||
@@ -227,19 +227,19 @@ export function refined<A extends Brand<any>>(
|
||||
(unbranded: Brand.Unbranded<A>) => Brand.BrandErrors
|
||||
]
|
||||
): Brand.Constructor<A> {
|
||||
const either: (unbranded: Brand.Unbranded<A>) => Either.Either<A, Brand.BrandErrors> = args.length === 2 ?
|
||||
(unbranded) => args[0](unbranded) ? Either.right(unbranded as A) : Either.left(args[1](unbranded)) :
|
||||
const result: (unbranded: Brand.Unbranded<A>) => Result.Result<A, Brand.BrandErrors> = args.length === 2 ?
|
||||
(unbranded) => args[0](unbranded) ? Result.ok(unbranded as A) : Result.err(args[1](unbranded)) :
|
||||
(unbranded) => {
|
||||
return Option.match(args[0](unbranded), {
|
||||
onNone: () => Either.right(unbranded as A),
|
||||
onSome: Either.left
|
||||
onNone: () => Result.ok(unbranded as A),
|
||||
onSome: Result.err
|
||||
})
|
||||
}
|
||||
return Object.assign((unbranded: Brand.Unbranded<A>) => Either.getOrThrowWith(either(unbranded), identity), {
|
||||
return Object.assign((unbranded: Brand.Unbranded<A>) => Result.getOrThrowWith(result(unbranded), identity), {
|
||||
[RefinedConstructorsTypeId]: RefinedConstructorsTypeId,
|
||||
option: (args: any) => Option.getRight(either(args)),
|
||||
either,
|
||||
is: (args: any): args is Brand.Unbranded<A> & A => Either.isRight(either(args))
|
||||
option: (args: any) => Option.getOk(result(args)),
|
||||
result,
|
||||
is: (args: any): args is Brand.Unbranded<A> & A => Result.isOk(result(args))
|
||||
}) as any
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ export const nominal = <A extends Brand<any>>(): Brand.Constructor<
|
||||
return Object.assign((args) => args, {
|
||||
[RefinedConstructorsTypeId]: RefinedConstructorsTypeId,
|
||||
option: (args: any) => Option.some(args),
|
||||
either: (args: any) => Either.right(args),
|
||||
result: (args: any) => Result.ok(args),
|
||||
is: (_args: any): _args is Brand.Unbranded<A> & A => true
|
||||
})
|
||||
}
|
||||
@@ -324,29 +324,29 @@ export const all: <Brands extends readonly [Brand.Constructor<any>, ...Array<Bra
|
||||
}[number]
|
||||
> extends infer X extends Brand<any> ? X : Brand<any>
|
||||
> => {
|
||||
const either = (args: any): Either.Either<any, Brand.BrandErrors> => {
|
||||
let result: Either.Either<any, Brand.BrandErrors> = Either.right(args)
|
||||
const result = (args: any): Result.Result<any, Brand.BrandErrors> => {
|
||||
let result: Result.Result<any, Brand.BrandErrors> = Result.ok(args)
|
||||
for (const brand of brands) {
|
||||
const nextResult = brand.either(args)
|
||||
if (Either.isLeft(result) && Either.isLeft(nextResult)) {
|
||||
result = Either.left([...result.left, ...nextResult.left])
|
||||
const nextResult = brand.result(args)
|
||||
if (Result.isErr(result) && Result.isErr(nextResult)) {
|
||||
result = Result.err([...result.err, ...nextResult.err])
|
||||
} else {
|
||||
result = Either.isLeft(result) ? result : nextResult
|
||||
result = Result.isErr(result) ? result : nextResult
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
// @ts-expect-error
|
||||
return Object.assign((args) =>
|
||||
Either.match(either(args), {
|
||||
onLeft: (e) => {
|
||||
Result.match(result(args), {
|
||||
onErr: (e) => {
|
||||
throw e
|
||||
},
|
||||
onRight: identity
|
||||
onOk: identity
|
||||
}), {
|
||||
[RefinedConstructorsTypeId]: RefinedConstructorsTypeId,
|
||||
option: (args: any) => Option.getRight(either(args)),
|
||||
either,
|
||||
is: (args: any): args is any => Either.isRight(either(args))
|
||||
option: (args: any) => Option.getOk(result(args)),
|
||||
result,
|
||||
is: (args: any): args is any => Result.isOk(result(args))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
*/
|
||||
import * as RA from "./Array.js"
|
||||
import type { NonEmptyReadonlyArray } from "./Array.js"
|
||||
import type { Either } from "./Either.js"
|
||||
import * as Equal from "./Equal.js"
|
||||
import * as Equivalence from "./Equivalence.js"
|
||||
import { dual, identity, pipe } from "./Function.js"
|
||||
@@ -17,6 +16,7 @@ import * as Order from "./Order.js"
|
||||
import type { Pipeable } from "./Pipeable.js"
|
||||
import { pipeArguments } from "./Pipeable.js"
|
||||
import { hasProperty, type Predicate, type Refinement } from "./Predicate.js"
|
||||
import type { Result } from "./Result.js"
|
||||
import type { Covariant, NoInfer } from "./Types.js"
|
||||
|
||||
const TypeId: unique symbol = Symbol.for("effect/Chunk") as TypeId
|
||||
@@ -991,9 +991,9 @@ export const partition: {
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const partitionMap: {
|
||||
<A, B, C>(f: (a: A) => Either<C, B>): (self: Chunk<A>) => [left: Chunk<B>, right: Chunk<C>]
|
||||
<A, B, C>(self: Chunk<A>, f: (a: A) => Either<C, B>): [left: Chunk<B>, right: Chunk<C>]
|
||||
} = dual(2, <A, B, C>(self: Chunk<A>, f: (a: A) => Either<C, B>): [left: Chunk<B>, right: Chunk<C>] =>
|
||||
<A, B, C>(f: (a: A) => Result<C, B>): (self: Chunk<A>) => [left: Chunk<B>, right: Chunk<C>]
|
||||
<A, B, C>(self: Chunk<A>, f: (a: A) => Result<C, B>): [left: Chunk<B>, right: Chunk<C>]
|
||||
} = dual(2, <A, B, C>(self: Chunk<A>, f: (a: A) => Result<C, B>): [left: Chunk<B>, right: Chunk<C>] =>
|
||||
pipe(
|
||||
RA.partitionMap(toReadonlyArray(self), f),
|
||||
([l, r]) => [unsafeFromArray(l), unsafeFromArray(r)]
|
||||
@@ -1005,7 +1005,7 @@ export const partitionMap: {
|
||||
* @category filtering
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const separate = <A, B>(self: Chunk<Either<B, A>>): [Chunk<A>, Chunk<B>] =>
|
||||
export const separate = <A, B>(self: Chunk<Result<B, A>>): [Chunk<A>, Chunk<B>] =>
|
||||
pipe(
|
||||
RA.separate(toReadonlyArray(self)),
|
||||
([l, r]) => [unsafeFromArray(l), unsafeFromArray(r)]
|
||||
|
||||
+26
-26
@@ -3,7 +3,6 @@
|
||||
*/
|
||||
import * as Arr from "./Array.js"
|
||||
import type * as DateTime from "./DateTime.js"
|
||||
import * as Either from "./Either.js"
|
||||
import * as Equal from "./Equal.js"
|
||||
import * as equivalence from "./Equivalence.js"
|
||||
import { constVoid, dual, pipe } from "./Function.js"
|
||||
@@ -14,6 +13,7 @@ import * as N from "./Number.js"
|
||||
import * as Option from "./Option.js"
|
||||
import { type Pipeable, pipeArguments } from "./Pipeable.js"
|
||||
import { hasProperty } from "./Predicate.js"
|
||||
import * as Result from "./Result.js"
|
||||
import * as String from "./String.js"
|
||||
import type { Mutable } from "./Types.js"
|
||||
|
||||
@@ -241,10 +241,10 @@ export const isCronParseError = (u: unknown): u is CronParseError => hasProperty
|
||||
* @example
|
||||
* ```ts
|
||||
* import * as assert from "node:assert"
|
||||
* import { Cron, Either } from "effect"
|
||||
* import { Cron, Result } from "effect"
|
||||
*
|
||||
* // At 04:00 on every day-of-month from 8 through 14.
|
||||
* assert.deepStrictEqual(Cron.parse("0 0 4 8-14 * *"), Either.right(Cron.make({
|
||||
* assert.deepStrictEqual(Cron.parse("0 0 4 8-14 * *"), Result.ok(Cron.make({
|
||||
* seconds: [0],
|
||||
* minutes: [0],
|
||||
* hours: [4],
|
||||
@@ -257,10 +257,10 @@ export const isCronParseError = (u: unknown): u is CronParseError => hasProperty
|
||||
* @since 2.0.0
|
||||
* @category constructors
|
||||
*/
|
||||
export const parse = (cron: string, tz?: DateTime.TimeZone | string): Either.Either<Cron, CronParseError> => {
|
||||
export const parse = (cron: string, tz?: DateTime.TimeZone | string): Result.Result<Cron, CronParseError> => {
|
||||
const segments = cron.split(" ").filter(String.isNonEmpty)
|
||||
if (segments.length !== 5 && segments.length !== 6) {
|
||||
return Either.left(CronParseError(`Invalid number of segments in cron expression`, cron))
|
||||
return Result.err(CronParseError(`Invalid number of segments in cron expression`, cron))
|
||||
}
|
||||
|
||||
if (segments.length === 5) {
|
||||
@@ -269,10 +269,10 @@ export const parse = (cron: string, tz?: DateTime.TimeZone | string): Either.Eit
|
||||
|
||||
const [seconds, minutes, hours, days, months, weekdays] = segments
|
||||
const zone = tz === undefined || dateTime.isTimeZone(tz) ?
|
||||
Either.right(tz) :
|
||||
Either.fromOption(dateTime.zoneFromString(tz), () => CronParseError(`Invalid time zone in cron expression`, tz))
|
||||
Result.ok(tz) :
|
||||
Result.fromOption(dateTime.zoneFromString(tz), () => CronParseError(`Invalid time zone in cron expression`, tz))
|
||||
|
||||
return Either.all({
|
||||
return Result.all({
|
||||
tz: zone,
|
||||
seconds: parseSegment(seconds, secondOptions),
|
||||
minutes: parseSegment(minutes, minuteOptions),
|
||||
@@ -280,7 +280,7 @@ export const parse = (cron: string, tz?: DateTime.TimeZone | string): Either.Eit
|
||||
days: parseSegment(days, dayOptions),
|
||||
months: parseSegment(months, monthOptions),
|
||||
weekdays: parseSegment(weekdays, weekdayOptions)
|
||||
}).pipe(Either.map(make))
|
||||
}).pipe(Result.map(make))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -308,7 +308,7 @@ export const parse = (cron: string, tz?: DateTime.TimeZone | string): Either.Eit
|
||||
* @since 2.0.0
|
||||
* @category constructors
|
||||
*/
|
||||
export const unsafeParse = (cron: string, tz?: DateTime.TimeZone | string): Cron => Either.getOrThrow(parse(cron, tz))
|
||||
export const unsafeParse = (cron: string, tz?: DateTime.TimeZone | string): Cron => Result.getOrThrow(parse(cron, tz))
|
||||
|
||||
/**
|
||||
* Checks if a given `Date` falls within an active `Cron` time window.
|
||||
@@ -321,9 +321,9 @@ export const unsafeParse = (cron: string, tz?: DateTime.TimeZone | string): Cron
|
||||
* @example
|
||||
* ```ts
|
||||
* import * as assert from "node:assert"
|
||||
* import { Cron, Either } from "effect"
|
||||
* import { Cron, Result } from "effect"
|
||||
*
|
||||
* const cron = Either.getOrThrow(Cron.parse("0 4 8-14 * *"))
|
||||
* const cron = Result.getOrThrow(Cron.parse("0 4 8-14 * *"))
|
||||
* assert.deepStrictEqual(Cron.match(cron, new Date("2021-01-08 04:00:00")), true)
|
||||
* assert.deepStrictEqual(Cron.match(cron, new Date("2021-01-08 05:00:00")), false)
|
||||
* ```
|
||||
@@ -380,10 +380,10 @@ const daysInMonth = (date: Date): number =>
|
||||
* @example
|
||||
* ```ts
|
||||
* import * as assert from "node:assert"
|
||||
* import { Cron, Either } from "effect"
|
||||
* import { Cron, Result } from "effect"
|
||||
*
|
||||
* const after = new Date("2021-01-01 00:00:00")
|
||||
* const cron = Either.getOrThrow(Cron.parse("0 4 8-14 * *"))
|
||||
* const cron = Result.getOrThrow(Cron.parse("0 4 8-14 * *"))
|
||||
* assert.deepStrictEqual(Cron.next(cron, after), new Date("2021-01-08 04:00:00"))
|
||||
* ```
|
||||
*
|
||||
@@ -618,7 +618,7 @@ const weekdayOptions: SegmentOptions = {
|
||||
const parseSegment = (
|
||||
input: string,
|
||||
options: SegmentOptions
|
||||
): Either.Either<ReadonlySet<number>, CronParseError> => {
|
||||
): Result.Result<ReadonlySet<number>, CronParseError> => {
|
||||
const capacity = options.max - options.min + 1
|
||||
const values = new Set<number>()
|
||||
const fields = input.split(",")
|
||||
@@ -626,18 +626,18 @@ const parseSegment = (
|
||||
for (const field of fields) {
|
||||
const [raw, step] = splitStep(field)
|
||||
if (raw === "*" && step === undefined) {
|
||||
return Either.right(new Set())
|
||||
return Result.ok(new Set())
|
||||
}
|
||||
|
||||
if (step !== undefined) {
|
||||
if (!Number.isInteger(step)) {
|
||||
return Either.left(CronParseError(`Expected step value to be a positive integer`, input))
|
||||
return Result.err(CronParseError(`Expected step value to be a positive integer`, input))
|
||||
}
|
||||
if (step < 1) {
|
||||
return Either.left(CronParseError(`Expected step value to be greater than 0`, input))
|
||||
return Result.err(CronParseError(`Expected step value to be greater than 0`, input))
|
||||
}
|
||||
if (step > options.max) {
|
||||
return Either.left(CronParseError(`Expected step value to be less than ${options.max}`, input))
|
||||
return Result.err(CronParseError(`Expected step value to be less than ${options.max}`, input))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -648,23 +648,23 @@ const parseSegment = (
|
||||
} else {
|
||||
const [left, right] = splitRange(raw, options.aliases)
|
||||
if (!Number.isInteger(left)) {
|
||||
return Either.left(CronParseError(`Expected a positive integer`, input))
|
||||
return Result.err(CronParseError(`Expected a positive integer`, input))
|
||||
}
|
||||
if (left < options.min || left > options.max) {
|
||||
return Either.left(CronParseError(`Expected a value between ${options.min} and ${options.max}`, input))
|
||||
return Result.err(CronParseError(`Expected a value between ${options.min} and ${options.max}`, input))
|
||||
}
|
||||
|
||||
if (right === undefined) {
|
||||
values.add(left)
|
||||
} else {
|
||||
if (!Number.isInteger(right)) {
|
||||
return Either.left(CronParseError(`Expected a positive integer`, input))
|
||||
return Result.err(CronParseError(`Expected a positive integer`, input))
|
||||
}
|
||||
if (right < options.min || right > options.max) {
|
||||
return Either.left(CronParseError(`Expected a value between ${options.min} and ${options.max}`, input))
|
||||
return Result.err(CronParseError(`Expected a value between ${options.min} and ${options.max}`, input))
|
||||
}
|
||||
if (left > right) {
|
||||
return Either.left(CronParseError(`Invalid value range`, input))
|
||||
return Result.err(CronParseError(`Invalid value range`, input))
|
||||
}
|
||||
|
||||
for (let i = left; i <= right; i += step ?? 1) {
|
||||
@@ -674,11 +674,11 @@ const parseSegment = (
|
||||
}
|
||||
|
||||
if (values.size >= capacity) {
|
||||
return Either.right(new Set())
|
||||
return Result.ok(new Set())
|
||||
}
|
||||
}
|
||||
|
||||
return Either.right(values)
|
||||
return Result.ok(values)
|
||||
}
|
||||
|
||||
const splitStep = (input: string): [string, number | undefined] => {
|
||||
|
||||
@@ -5,7 +5,6 @@ import type { IllegalArgumentError } from "./Cause.js"
|
||||
import * as Context from "./Context.js"
|
||||
import type * as Duration from "./Duration.js"
|
||||
import * as Effect from "./Effect.js"
|
||||
import type * as Either from "./Either.js"
|
||||
import type * as equivalence from "./Equivalence.js"
|
||||
import { dual, type LazyArg } from "./Function.js"
|
||||
import type { Inspectable } from "./Inspectable.js"
|
||||
@@ -14,6 +13,7 @@ import * as Layer from "./Layer.js"
|
||||
import type * as Option from "./Option.js"
|
||||
import type * as order from "./Order.js"
|
||||
import type { Pipeable } from "./Pipeable.js"
|
||||
import type * as Result from "./Result.js"
|
||||
|
||||
/**
|
||||
* @since 3.6.0
|
||||
@@ -649,10 +649,10 @@ export const distance: {
|
||||
* Calulate the difference between two `DateTime` values.
|
||||
*
|
||||
* If the `other` DateTime is before `self`, the result will be a negative
|
||||
* `Duration`, returned as a `Left`.
|
||||
* `Duration`, returned as a `Err`.
|
||||
*
|
||||
* If the `other` DateTime is after `self`, the result will be a positive
|
||||
* `Duration`, returned as a `Right`.
|
||||
* `Duration`, returned as a `Ok`.
|
||||
*
|
||||
* @since 3.6.0
|
||||
* @category comparisons
|
||||
@@ -664,18 +664,18 @@ export const distance: {
|
||||
* const now = yield* DateTime.now
|
||||
* const other = DateTime.add(now, { minutes: 1 })
|
||||
*
|
||||
* // returns Either.right(Duration.minutes(1))
|
||||
* DateTime.distanceDurationEither(now, other)
|
||||
* // returns Result.ok(Duration.minutes(1))
|
||||
* DateTime.distanceDurationResult(now, other)
|
||||
*
|
||||
* // returns Either.left(Duration.minutes(1))
|
||||
* DateTime.distanceDurationEither(other, now)
|
||||
* // returns Result.err(Duration.minutes(1))
|
||||
* DateTime.distanceDurationResult(other, now)
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export const distanceDurationEither: {
|
||||
(other: DateTime): (self: DateTime) => Either.Either<Duration.Duration, Duration.Duration>
|
||||
(self: DateTime, other: DateTime): Either.Either<Duration.Duration, Duration.Duration>
|
||||
} = Internal.distanceDurationEither
|
||||
export const distanceDurationResult: {
|
||||
(other: DateTime): (self: DateTime) => Result.Result<Duration.Duration, Duration.Duration>
|
||||
(self: DateTime, other: DateTime): Result.Result<Duration.Duration, Duration.Duration>
|
||||
} = Internal.distanceDurationResult
|
||||
|
||||
/**
|
||||
* Calulate the distance between two `DateTime` values.
|
||||
|
||||
@@ -6,7 +6,6 @@ import type * as Cause from "./Cause.js"
|
||||
import type { Clock } from "./Clock.js"
|
||||
import * as Context from "./Context.js"
|
||||
import * as Duration from "./Duration.js"
|
||||
import type * as Either from "./Either.js"
|
||||
import * as Exit from "./Exit.js"
|
||||
import type { Fiber } from "./Fiber.js"
|
||||
import { constant, dual, type LazyArg } from "./Function.js"
|
||||
@@ -303,15 +302,15 @@ export declare namespace All {
|
||||
* called "short-circuiting". If any effect in the collection fails, the
|
||||
* remaining effects will not run, and the error will be propagated. To change
|
||||
* this behavior, you can use the `mode` option, which allows all effects to run
|
||||
* and collect results as `Either` or `Option`.
|
||||
* and collect results as `Result` or `Option`.
|
||||
*
|
||||
* **The `mode` option**
|
||||
*
|
||||
* The `{ mode: "either" }` option changes the behavior of `Effect.all` to
|
||||
* The `{ mode: "result" }` option changes the behavior of `Effect.all` to
|
||||
* ensure all effects run, even if some fail. Instead of stopping on the first
|
||||
* failure, this mode collects both successes and failures, returning an array
|
||||
* of `Either` instances where each result is either a `Right` (success) or a
|
||||
* `Left` (failure).
|
||||
* of `Result` instances where each result is either an `Ok` (success) or a
|
||||
* `Err` (failure).
|
||||
*
|
||||
* Similarly, the `{ mode: "validate" }` option uses `Option` to indicate
|
||||
* success or failure. Each effect returns `None` for success and `Some` with
|
||||
@@ -1128,12 +1127,6 @@ export const withFiber: <A, E = never, R = never>(
|
||||
// Conversions
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* @since 4.0.0
|
||||
* @category Conversions
|
||||
*/
|
||||
export const fromEither: <A, E>(either: Either.Either<A, E>) => Effect<A, E> = internal.fromEither
|
||||
|
||||
/**
|
||||
* @since 4.0.0
|
||||
* @category Conversions
|
||||
@@ -1263,7 +1256,7 @@ export const flatMap: {
|
||||
* - An `Effect`
|
||||
* - A function returning an `Effect` (similar to {@link flatMap})
|
||||
*
|
||||
* **Note:** `andThen` works well with both `Option` and `Either` types,
|
||||
* **Note:** `andThen` works well with both `Option` and `Result` types,
|
||||
* treating them as effects.
|
||||
*
|
||||
* **Example** (Applying a Discount Based on Fetched Amount)
|
||||
@@ -1426,39 +1419,6 @@ export const tap: {
|
||||
): Effect<A, E | E1, R | R1>
|
||||
} = internal.tap
|
||||
|
||||
/**
|
||||
* Encapsulates both success and failure of an `Effect` into an `Either` type.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* This function converts an effect that may fail into an effect that always
|
||||
* succeeds, wrapping the outcome in an `Either` type. The result will be
|
||||
* `Either.Left` if the effect fails, containing the recoverable error, or
|
||||
* `Either.Right` if it succeeds, containing the result.
|
||||
*
|
||||
* Using this function, you can handle recoverable errors explicitly without
|
||||
* causing the effect to fail. This is particularly useful in scenarios where
|
||||
* you want to chain effects and manage both success and failure in the same
|
||||
* logical flow.
|
||||
*
|
||||
* It's important to note that unrecoverable errors, often referred to as
|
||||
* "defects," are still thrown and not captured within the `Either` type. Only
|
||||
* failures that are explicitly represented as recoverable errors in the effect
|
||||
* are encapsulated.
|
||||
*
|
||||
* The resulting effect cannot fail directly because all recoverable failures
|
||||
* are represented inside the `Either` type.
|
||||
*
|
||||
* @see {@link option} for a version that uses `Option` instead.
|
||||
* @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`.
|
||||
*
|
||||
* @since 2.0.0
|
||||
* @category Outcome Encapsulation
|
||||
*/
|
||||
export const either: <A, E, R>(
|
||||
self: Effect<A, E, R>
|
||||
) => Effect<Either.Either<A, E>, never, R> = internal.either
|
||||
|
||||
/**
|
||||
* Encapsulates both success and failure of an `Effect` into a `Result` type.
|
||||
*
|
||||
@@ -1504,7 +1464,7 @@ export const result: <A, E, R>(self: Effect<A, E, R>) => Effect<Result.Result<A,
|
||||
* the effect is structured to never fail directly.
|
||||
*
|
||||
* @see {@link option} for a version that uses `Option` instead.
|
||||
* @see {@link either} for a version that uses `Either` instead.
|
||||
* @see {@link result} for a version that uses `Result` instead.
|
||||
*
|
||||
* @since 2.0.0
|
||||
* @category Outcome Encapsulation
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,11 +7,11 @@
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
import * as Either from "./Either.js"
|
||||
import * as Base64 from "./internal/encoding/base64.js"
|
||||
import * as Base64Url from "./internal/encoding/base64Url.js"
|
||||
import * as Common from "./internal/encoding/common.js"
|
||||
import * as Hex from "./internal/encoding/hex.js"
|
||||
import * as Result from "./Result.js"
|
||||
|
||||
/**
|
||||
* Encodes the given value into a base64 (RFC4648) `string`.
|
||||
@@ -28,7 +28,7 @@ export const encodeBase64: (input: Uint8Array | string) => string = (input) =>
|
||||
* @category decoding
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const decodeBase64 = (str: string): Either.Either<Uint8Array, DecodeException> => Base64.decode(str)
|
||||
export const decodeBase64 = (str: string): Result.Result<Uint8Array, DecodeException> => Base64.decode(str)
|
||||
|
||||
/**
|
||||
* Decodes a base64 (RFC4648) encoded `string` into a UTF-8 `string`.
|
||||
@@ -36,7 +36,7 @@ export const decodeBase64 = (str: string): Either.Either<Uint8Array, DecodeExcep
|
||||
* @category decoding
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const decodeBase64String = (str: string) => Either.map(decodeBase64(str), (_) => Common.decoder.decode(_))
|
||||
export const decodeBase64String = (str: string) => Result.map(decodeBase64(str), (_) => Common.decoder.decode(_))
|
||||
|
||||
/**
|
||||
* Encodes the given value into a base64 (URL) `string`.
|
||||
@@ -53,7 +53,7 @@ export const encodeBase64Url: (input: Uint8Array | string) => string = (input) =
|
||||
* @category decoding
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const decodeBase64Url = (str: string): Either.Either<Uint8Array, DecodeException> => Base64Url.decode(str)
|
||||
export const decodeBase64Url = (str: string): Result.Result<Uint8Array, DecodeException> => Base64Url.decode(str)
|
||||
|
||||
/**
|
||||
* Decodes a base64 (URL) encoded `string` into a UTF-8 `string`.
|
||||
@@ -61,7 +61,7 @@ export const decodeBase64Url = (str: string): Either.Either<Uint8Array, DecodeEx
|
||||
* @category decoding
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const decodeBase64UrlString = (str: string) => Either.map(decodeBase64Url(str), (_) => Common.decoder.decode(_))
|
||||
export const decodeBase64UrlString = (str: string) => Result.map(decodeBase64Url(str), (_) => Common.decoder.decode(_))
|
||||
|
||||
/**
|
||||
* Encodes the given value into a hex `string`.
|
||||
@@ -78,7 +78,7 @@ export const encodeHex: (input: Uint8Array | string) => string = (input) =>
|
||||
* @category decoding
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const decodeHex = (str: string): Either.Either<Uint8Array, DecodeException> => Hex.decode(str)
|
||||
export const decodeHex = (str: string): Result.Result<Uint8Array, DecodeException> => Hex.decode(str)
|
||||
|
||||
/**
|
||||
* Decodes a hex encoded `string` into a UTF-8 `string`.
|
||||
@@ -86,7 +86,7 @@ export const decodeHex = (str: string): Either.Either<Uint8Array, DecodeExceptio
|
||||
* @category decoding
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const decodeHexString = (str: string) => Either.map(decodeHex(str), (_) => Common.decoder.decode(_))
|
||||
export const decodeHexString = (str: string) => Result.map(decodeHex(str), (_) => Common.decoder.decode(_))
|
||||
|
||||
/**
|
||||
* @since 2.0.0
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
*/
|
||||
|
||||
import type { NonEmptyArray } from "./Array.js"
|
||||
import type { Either } from "./Either.js"
|
||||
import * as E from "./Either.js"
|
||||
import * as Equal from "./Equal.js"
|
||||
import { dual, identity } from "./Function.js"
|
||||
import type { Option } from "./Option.js"
|
||||
import * as O from "./Option.js"
|
||||
import { isBoolean } from "./Predicate.js"
|
||||
import type * as Record from "./Record.js"
|
||||
import type { Result } from "./Result.js"
|
||||
import * as R from "./Result.js"
|
||||
import * as Tuple from "./Tuple.js"
|
||||
import type { NoInfer } from "./Types.js"
|
||||
|
||||
@@ -851,15 +851,15 @@ export const filterMapWhile: {
|
||||
export const getSomes: <A>(self: Iterable<Option<A>>) => Iterable<A> = filterMap(identity)
|
||||
|
||||
/**
|
||||
* Retrieves the `Left` values from an `Iterable` of `Either`s.
|
||||
* Retrieves the `Err` values from an `Iterable` of `Result`s.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import * as assert from "node:assert"
|
||||
* import { Iterable, Either } from "effect"
|
||||
* import { Iterable, Result } from "effect"
|
||||
*
|
||||
* assert.deepStrictEqual(
|
||||
* Array.from(Iterable.getLefts([Either.right(1), Either.left("err"), Either.right(2)])),
|
||||
* Array.from(Iterable.getErrs([Result.ok(1), Result.err("err"), Result.ok(2)])),
|
||||
* ["err"]
|
||||
* )
|
||||
* ```
|
||||
@@ -867,18 +867,18 @@ export const getSomes: <A>(self: Iterable<Option<A>>) => Iterable<A> = filterMap
|
||||
* @category filtering
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const getLefts = <R, L>(self: Iterable<Either<R, L>>): Iterable<L> => filterMap(self, E.getLeft)
|
||||
export const getErrs = <R, L>(self: Iterable<Result<R, L>>): Iterable<L> => filterMap(self, R.getErr)
|
||||
|
||||
/**
|
||||
* Retrieves the `Right` values from an `Iterable` of `Either`s.
|
||||
* Retrieves the `Ok` values from an `Iterable` of `Result`s.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import * as assert from "node:assert"
|
||||
* import { Iterable, Either } from "effect"
|
||||
* import { Iterable, Result } from "effect"
|
||||
*
|
||||
* assert.deepStrictEqual(
|
||||
* Array.from(Iterable.getRights([Either.right(1), Either.left("err"), Either.right(2)])),
|
||||
* Array.from(Iterable.getOks([Result.ok(1), Result.err("err"), Result.ok(2)])),
|
||||
* [1, 2]
|
||||
* )
|
||||
* ```
|
||||
@@ -886,7 +886,7 @@ export const getLefts = <R, L>(self: Iterable<Either<R, L>>): Iterable<L> => fil
|
||||
* @category filtering
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const getRights = <R, L>(self: Iterable<Either<R, L>>): Iterable<R> => filterMap(self, E.getRight)
|
||||
export const getOks = <R, L>(self: Iterable<Result<R, L>>): Iterable<R> => filterMap(self, R.getOk)
|
||||
|
||||
/**
|
||||
* @category filtering
|
||||
|
||||
@@ -26,11 +26,11 @@
|
||||
*
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import type * as Either from "./Either.js"
|
||||
import * as internal from "./internal/matcher.js"
|
||||
import type * as Option from "./Option.js"
|
||||
import type { Pipeable } from "./Pipeable.js"
|
||||
import * as Predicate from "./Predicate.js"
|
||||
import type * as Result from "./Result.js"
|
||||
import type * as T from "./Types.js"
|
||||
import type { Unify } from "./Unify.js"
|
||||
|
||||
@@ -120,7 +120,7 @@ export interface ValueMatcher<in Input, Filters, out Remaining, out Result, Prov
|
||||
readonly _return: T.Covariant<Return>
|
||||
}
|
||||
readonly provided: Provided
|
||||
readonly value: Either.Either<Provided, Remaining>
|
||||
readonly value: Result.Result<Provided, Remaining>
|
||||
add<I, R, RA, A, Pr>(_case: Case): ValueMatcher<I, R, RA, A, Pr>
|
||||
}
|
||||
|
||||
@@ -710,7 +710,6 @@ export const discriminatorsExhaustive: <D extends string>(
|
||||
* | { readonly _tag: "error"; readonly error: Error }
|
||||
* | { readonly _tag: "cancel" }
|
||||
*
|
||||
* // Create a Matcher for Either<number, string>
|
||||
* const match = Match.type<Event>().pipe(
|
||||
* // Match either "fetch" or "success"
|
||||
* Match.tag("fetch", "success", () => `Ok!`),
|
||||
@@ -1109,7 +1108,7 @@ export const orElse: <RA, Ret, F extends (_: RA) => Ret>(
|
||||
self: Matcher<I, R, RA, A, Pr, Ret>
|
||||
) => [Pr] extends [never] ? (input: I) => Unify<ReturnType<F> | A> : Unify<ReturnType<F> | A> = internal.orElse
|
||||
|
||||
// TODO(4.0): Rename to "orThrow"? Like Either.getOrThrow
|
||||
// TODO(4.0): Rename to "orThrow"? Like Result.getOrThrow
|
||||
/**
|
||||
* Throws an error if no pattern matches.
|
||||
*
|
||||
@@ -1131,21 +1130,21 @@ export const orElseAbsurd: <I, R, RA, A, Pr, Ret>(
|
||||
) => [Pr] extends [never] ? (input: I) => Unify<A> : Unify<A> = internal.orElseAbsurd
|
||||
|
||||
/**
|
||||
* Wraps the match result in an `Either`, distinguishing matched and unmatched
|
||||
* Wraps the match result in a `Result`, distinguishing matched and unmatched
|
||||
* cases.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* This function ensures that the result of a matcher is always wrapped in an
|
||||
* `Either`, allowing clear differentiation between successful matches
|
||||
* (`Right(value)`) and cases where no pattern matched (`Left(unmatched
|
||||
* `Result`, allowing clear differentiation between successful matches
|
||||
* (`Ok(value)`) and cases where no pattern matched (`Err(unmatched
|
||||
* value)`).
|
||||
*
|
||||
* This approach is particularly useful when handling optional values or when an
|
||||
* unmatched case should be explicitly handled rather than returning a default
|
||||
* value or throwing an error.
|
||||
*
|
||||
* **Example** (Extracting a User Role with `Match.either`)
|
||||
* **Example** (Extracting a User Role with `Match.result`)
|
||||
*
|
||||
* ```ts
|
||||
* import { Match } from "effect"
|
||||
@@ -1156,22 +1155,22 @@ export const orElseAbsurd: <I, R, RA, A, Pr, Ret>(
|
||||
* const getRole = Match.type<User>().pipe(
|
||||
* Match.when({ role: "admin" }, () => "Has full access"),
|
||||
* Match.when({ role: "editor" }, () => "Can edit content"),
|
||||
* Match.either // Wrap the result in an Either
|
||||
* Match.result // Wrap the result in an Result
|
||||
* )
|
||||
*
|
||||
* console.log(getRole({ role: "admin" }))
|
||||
* // Output: { _id: 'Either', _tag: 'Right', right: 'Has full access' }
|
||||
* // Output: { _id: 'Result', _tag: 'Ok', ok: 'Has full access' }
|
||||
*
|
||||
* console.log(getRole({ role: "viewer" }))
|
||||
* // Output: { _id: 'Either', _tag: 'Left', left: { role: 'viewer' } }
|
||||
* // Output: { _id: 'Result', _tag: 'Err', err: { role: 'viewer' } }
|
||||
* ```
|
||||
*
|
||||
* @category Completion
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const either: <I, F, R, A, Pr, Ret>(
|
||||
export const result: <I, F, R, A, Pr, Ret>(
|
||||
self: Matcher<I, F, R, A, Pr, Ret>
|
||||
) => [Pr] extends [never] ? (input: I) => Either.Either<Unify<A>, R> : Either.Either<Unify<A>, R> = internal.either
|
||||
) => [Pr] extends [never] ? (input: I) => Result.Result<Unify<A>, R> : Result.Result<Unify<A>, R> = internal.result
|
||||
|
||||
/**
|
||||
* Wraps the match result in an `Option`, representing an optional match.
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
*/
|
||||
import type { NoSuchElementError } from "./Cause.js"
|
||||
import type { EffectIterator, Yieldable } from "./Effect.js"
|
||||
import type { Either } from "./Either.js"
|
||||
import * as Equal from "./Equal.js"
|
||||
import * as Equivalence from "./Equivalence.js"
|
||||
import type { LazyArg } from "./Function.js"
|
||||
@@ -11,12 +10,13 @@ import { constNull, constUndefined, dual, identity, isFunction } from "./Functio
|
||||
import type { TypeLambda } from "./HKT.js"
|
||||
import type { Inspectable } from "./Inspectable.js"
|
||||
import * as doNotation from "./internal/doNotation.js"
|
||||
import * as either from "./internal/either.js"
|
||||
import * as option from "./internal/option.js"
|
||||
import * as result from "./internal/result.js"
|
||||
import type { Order } from "./Order.js"
|
||||
import * as order from "./Order.js"
|
||||
import type { Pipeable } from "./Pipeable.js"
|
||||
import type { Predicate, Refinement } from "./Predicate.js"
|
||||
import type { Result } from "./Result.js"
|
||||
import type { Covariant, NoInfer, NotFunction } from "./Types.js"
|
||||
import type * as Unify from "./Unify.js"
|
||||
import * as Gen from "./Utils.js"
|
||||
@@ -399,74 +399,74 @@ export const fromIterable = <A>(collection: Iterable<A>): Option<A> => {
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an `Either` into an `Option` by discarding the error and extracting
|
||||
* Converts a `Result` into an `Option` by discarding the error and extracting
|
||||
* the right value.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* This function takes an `Either` and returns an `Option` based on its value:
|
||||
* This function takes an `Result` and returns an `Option` based on its value:
|
||||
*
|
||||
* - If the `Either` is a `Right`, its value is wrapped in a `Some` and
|
||||
* - If the `Result` is a `Ok`, its value is wrapped in a `Some` and
|
||||
* returned.
|
||||
* - If the `Either` is a `Left`, the error is discarded, and `None` is
|
||||
* - If the `Result` is a `Err`, the error is discarded, and `None` is
|
||||
* returned.
|
||||
*
|
||||
* This is particularly useful when you only care about the success case
|
||||
* (`Right`) of an `Either` and want to handle the result using `Option`. By
|
||||
* using this function, you can convert `Either` into a simpler structure for
|
||||
* (`Ok`) of an `Result` and want to handle the result using `Option`. By
|
||||
* using this function, you can convert `Result` into a simpler structure for
|
||||
* cases where error handling is not required.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { Either, Option } from "effect"
|
||||
* import { Result, Option } from "effect"
|
||||
*
|
||||
* console.log(Option.getRight(Either.right("ok")))
|
||||
* console.log(Option.getOk(Result.ok("ok")))
|
||||
* // Output: { _id: 'Option', _tag: 'Some', value: 'ok' }
|
||||
*
|
||||
* console.log(Option.getRight(Either.left("err")))
|
||||
* console.log(Option.getOk(Result.err("err")))
|
||||
* // Output: { _id: 'Option', _tag: 'None' }
|
||||
* ```
|
||||
*
|
||||
* @see {@link getLeft} for the opposite operation.
|
||||
* @see {@link getErr} for the opposite operation.
|
||||
*
|
||||
* @category Conversions
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const getRight: <R, L>(self: Either<R, L>) => Option<R> = either.getRight
|
||||
export const getOk: <A, E>(self: Result<A, E>) => Option<A> = result.getOk
|
||||
|
||||
/**
|
||||
* Converts an `Either` into an `Option` by discarding the right value and
|
||||
* Converts a `Result` into an `Option` by discarding the right value and
|
||||
* extracting the left value.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* This function transforms an `Either` into an `Option` as follows:
|
||||
* This function transforms an `Result` into an `Option` as follows:
|
||||
*
|
||||
* - If the `Either` is a `Left`, its value is wrapped in a `Some` and returned.
|
||||
* - If the `Either` is a `Right`, the value is discarded, and `None` is
|
||||
* - If the `Result` is a `Err`, its value is wrapped in a `Some` and returned.
|
||||
* - If the `Result` is a `Ok`, the value is discarded, and `None` is
|
||||
* returned.
|
||||
*
|
||||
* This utility is useful when you only care about the error case (`Left`) of an
|
||||
* `Either` and want to handle it as an `Option`. By discarding the right value,
|
||||
* This utility is useful when you only care about the error case (`Err`) of an
|
||||
* `Result` and want to handle it as an `Option`. By discarding the right value,
|
||||
* it simplifies error-focused workflows.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { Either, Option } from "effect"
|
||||
* import { Result, Option } from "effect"
|
||||
*
|
||||
* console.log(Option.getLeft(Either.right("ok")))
|
||||
* console.log(Option.getErr(Result.ok("ok")))
|
||||
* // Output: { _id: 'Option', _tag: 'None' }
|
||||
*
|
||||
* console.log(Option.getLeft(Either.left("err")))
|
||||
* console.log(Option.getErr(Result.err("err")))
|
||||
* // Output: { _id: 'Option', _tag: 'Some', value: 'err' }
|
||||
* ```
|
||||
*
|
||||
* @see {@link getRight} for the opposite operation.
|
||||
* @see {@link getOk} for the opposite operation.
|
||||
*
|
||||
* @category Conversions
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const getLeft: <R, L>(self: Either<R, L>) => Option<L> = either.getLeft
|
||||
export const getErr: <A, E>(self: Result<A, E>) => Option<E> = result.getErr
|
||||
|
||||
/**
|
||||
* Returns the value contained in the `Option` if it is `Some`, otherwise
|
||||
@@ -591,20 +591,20 @@ export const orElseSome: {
|
||||
)
|
||||
|
||||
/**
|
||||
* Similar to {@link orElse}, but returns an `Either` wrapped in an `Option` to
|
||||
* Similar to {@link orElse}, but returns an `Result` wrapped in an `Option` to
|
||||
* indicate the source of the value.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* This function allows you to provide a fallback `Option` in case the current
|
||||
* `Option` (`self`) is `None`. However, unlike `orElse`, it returns the value
|
||||
* wrapped in an `Either` object, providing additional information about where
|
||||
* wrapped in an `Result` object, providing additional information about where
|
||||
* the value came from:
|
||||
*
|
||||
* - If the value is from the fallback `Option` (`that`), it is wrapped in an
|
||||
* `Either.right`.
|
||||
* `Result.ok`.
|
||||
* - If the value is from the original `Option` (`self`), it is wrapped in an
|
||||
* `Either.left`.
|
||||
* `Result.err`.
|
||||
*
|
||||
* This is especially useful when you need to differentiate between values
|
||||
* originating from the primary `Option` and those coming from the fallback,
|
||||
@@ -613,13 +613,13 @@ export const orElseSome: {
|
||||
* @category Error handling
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const orElseEither: {
|
||||
<B>(that: LazyArg<Option<B>>): <A>(self: Option<A>) => Option<Either<B, A>>
|
||||
<A, B>(self: Option<A>, that: LazyArg<Option<B>>): Option<Either<B, A>>
|
||||
export const orElseResult: {
|
||||
<B>(that: LazyArg<Option<B>>): <A>(self: Option<A>) => Option<Result<B, A>>
|
||||
<A, B>(self: Option<A>, that: LazyArg<Option<B>>): Option<Result<B, A>>
|
||||
} = dual(
|
||||
2,
|
||||
<A, B>(self: Option<A>, that: LazyArg<Option<B>>): Option<Either<B, A>> =>
|
||||
isNone(self) ? map(that(), either.right) : map(self, either.left)
|
||||
<A, B>(self: Option<A>, that: LazyArg<Option<B>>): Option<Result<B, A>> =>
|
||||
isNone(self) ? map(that(), result.ok) : map(self, result.err)
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -1550,17 +1550,17 @@ export const toArray = <A>(self: Option<A>): Array<A> => isNone(self) ? [] : [se
|
||||
|
||||
/**
|
||||
* Splits an `Option` into two `Option`s based on the result of a mapping
|
||||
* function that produces an `Either`.
|
||||
* function that produces an `Result`.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* This function takes an `Option` and a mapping function `f` that converts its
|
||||
* value into an `Either`. It returns a tuple of two `Option`s:
|
||||
* value into an `Result`. It returns a tuple of two `Option`s:
|
||||
*
|
||||
* - The first `Option` (`left`) contains the value from the `Left` side of the
|
||||
* `Either` if it exists, otherwise `None`.
|
||||
* - The second `Option` (`right`) contains the value from the `Right` side of
|
||||
* the `Either` if it exists, otherwise `None`.
|
||||
* - The first `Option` (`left`) contains the value from the `Err` side of the
|
||||
* `Result` if it exists, otherwise `None`.
|
||||
* - The second `Option` (`right`) contains the value from the `Ok` side of
|
||||
* the `Result` if it exists, otherwise `None`.
|
||||
*
|
||||
* If the input `Option` is `None`, both returned `Option`s are `None`.
|
||||
*
|
||||
@@ -1571,17 +1571,17 @@ export const toArray = <A>(self: Option<A>): Array<A> => isNone(self) ? [] : [se
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const partitionMap: {
|
||||
<A, B, C>(f: (a: A) => Either<C, B>): (self: Option<A>) => [left: Option<B>, right: Option<C>]
|
||||
<A, B, C>(self: Option<A>, f: (a: A) => Either<C, B>): [left: Option<B>, right: Option<C>]
|
||||
<A, B, C>(f: (a: A) => Result<C, B>): (self: Option<A>) => [left: Option<B>, right: Option<C>]
|
||||
<A, B, C>(self: Option<A>, f: (a: A) => Result<C, B>): [left: Option<B>, right: Option<C>]
|
||||
} = dual(2, <A, B, C>(
|
||||
self: Option<A>,
|
||||
f: (a: A) => Either<C, B>
|
||||
f: (a: A) => Result<C, B>
|
||||
): [excluded: Option<B>, satisfying: Option<C>] => {
|
||||
if (isNone(self)) {
|
||||
return [none(), none()]
|
||||
}
|
||||
const e = f(self.value)
|
||||
return either.isLeft(e) ? [some(e.left), none()] : [none(), some(e.right)]
|
||||
return result.isErr(e) ? [some(e.err), none()] : [none(), some(e.ok)]
|
||||
})
|
||||
|
||||
// TODO(4.0): remove?
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
* @since 2.0.0
|
||||
*/
|
||||
|
||||
import type { Either } from "./Either.js"
|
||||
import * as E from "./Either.js"
|
||||
import * as Equal from "./Equal.js"
|
||||
import type { Equivalence } from "./Equivalence.js"
|
||||
import { dual, identity } from "./Function.js"
|
||||
import type { TypeLambda } from "./HKT.js"
|
||||
import * as Option from "./Option.js"
|
||||
import type { Result } from "./Result.js"
|
||||
import * as R from "./Result.js"
|
||||
import type { NoInfer } from "./Types.js"
|
||||
|
||||
/**
|
||||
@@ -717,15 +717,15 @@ export const getSomes: <K extends string, A>(
|
||||
)
|
||||
|
||||
/**
|
||||
* Given a record with `Either` values, returns a new record containing only the `Left` values, preserving the original keys.
|
||||
* Given a record with `Result` values, returns a new record containing only the `Err` values, preserving the original keys.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import * as assert from "node:assert"
|
||||
* import { Record, Either } from "effect"
|
||||
* import { Record, Result } from "effect"
|
||||
*
|
||||
* assert.deepStrictEqual(
|
||||
* Record.getLefts({ a: Either.right(1), b: Either.left("err"), c: Either.right(2) }),
|
||||
* Record.getErrs({ a: Result.ok(1), b: Result.err("err"), c: Result.ok(2) }),
|
||||
* { b: "err" }
|
||||
* )
|
||||
* ```
|
||||
@@ -733,14 +733,14 @@ export const getSomes: <K extends string, A>(
|
||||
* @category filtering
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const getLefts = <K extends string, R, L>(
|
||||
self: ReadonlyRecord<K, Either<R, L>>
|
||||
export const getErrs = <K extends string, R, L>(
|
||||
self: ReadonlyRecord<K, Result<R, L>>
|
||||
): Record<ReadonlyRecord.NonLiteralKey<K>, L> => {
|
||||
const out: Record<string, L> = empty()
|
||||
for (const key of keys(self)) {
|
||||
const value = self[key]
|
||||
if (E.isLeft(value)) {
|
||||
out[key] = value.left
|
||||
if (R.isErr(value)) {
|
||||
out[key] = value.err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -748,15 +748,15 @@ export const getLefts = <K extends string, R, L>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a record with `Either` values, returns a new record containing only the `Right` values, preserving the original keys.
|
||||
* Given a record with `Result` values, returns a new record containing only the `Ok` values, preserving the original keys.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import * as assert from "node:assert"
|
||||
* import { Record, Either } from "effect"
|
||||
* import { Record, Result } from "effect"
|
||||
*
|
||||
* assert.deepStrictEqual(
|
||||
* Record.getRights({ a: Either.right(1), b: Either.left("err"), c: Either.right(2) }),
|
||||
* Record.getOks({ a: Result.ok(1), b: Result.err("err"), c: Result.ok(2) }),
|
||||
* { a: 1, c: 2 }
|
||||
* )
|
||||
* ```
|
||||
@@ -764,14 +764,14 @@ export const getLefts = <K extends string, R, L>(
|
||||
* @category filtering
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const getRights = <K extends string, R, L>(
|
||||
self: ReadonlyRecord<K, Either<R, L>>
|
||||
export const getOks = <K extends string, R, L>(
|
||||
self: ReadonlyRecord<K, Result<R, L>>
|
||||
): Record<string, R> => {
|
||||
const out: Record<string, R> = empty()
|
||||
for (const key of keys(self)) {
|
||||
const value = self[key]
|
||||
if (E.isRight(value)) {
|
||||
out[key] = value.right
|
||||
if (R.isOk(value)) {
|
||||
out[key] = value.ok
|
||||
}
|
||||
}
|
||||
|
||||
@@ -784,10 +784,10 @@ export const getRights = <K extends string, R, L>(
|
||||
* @example
|
||||
* ```ts
|
||||
* import * as assert from "node:assert"
|
||||
* import { Record, Either } from "effect"
|
||||
* import { Record, Result } from "effect"
|
||||
*
|
||||
* const x = { a: 1, b: 2, c: 3 }
|
||||
* const f = (n: number) => (n % 2 === 0 ? Either.right(n) : Either.left(n))
|
||||
* const f = (n: number) => (n % 2 === 0 ? Result.ok(n) : Result.err(n))
|
||||
* assert.deepStrictEqual(Record.partitionMap(x, f), [{ a: 1, c: 3 }, { b: 2}])
|
||||
* ```
|
||||
*
|
||||
@@ -796,28 +796,28 @@ export const getRights = <K extends string, R, L>(
|
||||
*/
|
||||
export const partitionMap: {
|
||||
<K extends string, A, B, C>(
|
||||
f: (a: A, key: K) => Either<C, B>
|
||||
f: (a: A, key: K) => Result<C, B>
|
||||
): (
|
||||
self: ReadonlyRecord<K, A>
|
||||
) => [left: Record<ReadonlyRecord.NonLiteralKey<K>, B>, right: Record<ReadonlyRecord.NonLiteralKey<K>, C>]
|
||||
<K extends string, A, B, C>(
|
||||
self: ReadonlyRecord<K, A>,
|
||||
f: (a: A, key: K) => Either<C, B>
|
||||
f: (a: A, key: K) => Result<C, B>
|
||||
): [left: Record<ReadonlyRecord.NonLiteralKey<K>, B>, right: Record<ReadonlyRecord.NonLiteralKey<K>, C>]
|
||||
} = dual(
|
||||
2,
|
||||
<K extends string, A, B, C>(
|
||||
self: ReadonlyRecord<K, A>,
|
||||
f: (a: A, key: K) => Either<C, B>
|
||||
f: (a: A, key: K) => Result<C, B>
|
||||
): [left: Record<ReadonlyRecord.NonLiteralKey<K>, B>, right: Record<ReadonlyRecord.NonLiteralKey<K>, C>] => {
|
||||
const left: Record<string, B> = empty()
|
||||
const right: Record<string, C> = empty()
|
||||
for (const key of keys(self)) {
|
||||
const e = f(self[key], key)
|
||||
if (E.isLeft(e)) {
|
||||
left[key] = e.left
|
||||
if (R.isErr(e)) {
|
||||
left[key] = e.err
|
||||
} else {
|
||||
right[key] = e.right
|
||||
right[key] = e.ok
|
||||
}
|
||||
}
|
||||
return [left, right]
|
||||
@@ -825,16 +825,16 @@ export const partitionMap: {
|
||||
)
|
||||
|
||||
/**
|
||||
* Partitions a record of `Either` values into two separate records,
|
||||
* one with the `Left` values and one with the `Right` values.
|
||||
* Partitions a record of `Result` values into two separate records,
|
||||
* one with the `Err` values and one with the `Ok` values.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import * as assert from "node:assert"
|
||||
* import { Record, Either } from "effect"
|
||||
* import { Record, Result } from "effect"
|
||||
*
|
||||
* assert.deepStrictEqual(
|
||||
* Record.separate({ a: Either.left("e"), b: Either.right(1) }),
|
||||
* Record.separate({ a: Result.err("e"), b: Result.ok(1) }),
|
||||
* [{ a: "e" }, { b: 1 }]
|
||||
* )
|
||||
* ```
|
||||
@@ -843,7 +843,7 @@ export const partitionMap: {
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export const separate: <K extends string, A, B>(
|
||||
self: ReadonlyRecord<K, Either<B, A>>
|
||||
self: ReadonlyRecord<K, Result<B, A>>
|
||||
) => [Record<ReadonlyRecord.NonLiteralKey<K>, A>, Record<ReadonlyRecord.NonLiteralKey<K>, B>] = partitionMap(identity)
|
||||
|
||||
/**
|
||||
|
||||
@@ -441,25 +441,25 @@ export const match: {
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const liftPredicate: {
|
||||
<A, B extends A, E>(refinement: Refinement<A, B>, orLeftWith: (a: A) => E): (a: A) => Result<B, E>
|
||||
<A, B extends A, E>(refinement: Refinement<A, B>, orErrWith: (a: A) => E): (a: A) => Result<B, E>
|
||||
<B extends A, E, A = B>(
|
||||
predicate: Predicate<A>,
|
||||
orLeftWith: (a: A) => E
|
||||
orErrWith: (a: A) => E
|
||||
): (a: B) => Result<B, E>
|
||||
<A, E, B extends A>(
|
||||
self: A,
|
||||
refinement: Refinement<A, B>,
|
||||
orLeftWith: (a: A) => E
|
||||
orErrWith: (a: A) => E
|
||||
): Result<B, E>
|
||||
<B extends A, E, A = B>(
|
||||
self: B,
|
||||
predicate: Predicate<A>,
|
||||
orLeftWith: (a: A) => E
|
||||
orErrWith: (a: A) => E
|
||||
): Result<B, E>
|
||||
} = dual(
|
||||
3,
|
||||
<A, E>(a: A, predicate: Predicate<A>, orLeftWith: (a: A) => E): Result<A, E> =>
|
||||
predicate(a) ? ok(a) : err(orLeftWith(a))
|
||||
<A, E>(a: A, predicate: Predicate<A>, orErrWith: (a: A) => E): Result<A, E> =>
|
||||
predicate(a) ? ok(a) : err(orErrWith(a))
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -535,11 +535,11 @@ export const merge: <A, E>(self: Result<A, E>) => E | A = match({ onErr: identit
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const getOrElse: {
|
||||
<E, A2>(onLeft: (err: E) => A2): <A>(self: Result<A, E>) => A2 | A
|
||||
<A, E, A2>(self: Result<A, E>, onLeft: (err: E) => A2): A | A2
|
||||
<E, A2>(onErr: (err: E) => A2): <A>(self: Result<A, E>) => A2 | A
|
||||
<A, E, A2>(self: Result<A, E>, onErr: (err: E) => A2): A | A2
|
||||
} = dual(
|
||||
2,
|
||||
<A, E, A2>(self: Result<A, E>, onLeft: (err: E) => A2): A | A2 => isErr(self) ? onLeft(self.err) : self.ok
|
||||
<A, E, A2>(self: Result<A, E>, onErr: (err: E) => A2): A | A2 => isErr(self) ? onErr(self.err) : self.ok
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -932,7 +932,7 @@ export {
|
||||
*
|
||||
* This function transforms an `Option<Result<A, E>>` into an
|
||||
* `Result<Option<A>, E>`. If the `Option` is `None`, the resulting `Result`
|
||||
* will be a `Right` with a `None` value. If the `Option` is `Some`, the
|
||||
* will be a `Ok` with a `None` value. If the `Option` is `Some`, the
|
||||
* inner `Result` will be executed, and its result wrapped in a `Some`.
|
||||
*
|
||||
* @example
|
||||
|
||||
@@ -5,7 +5,6 @@ import * as Cron from "./Cron.js"
|
||||
import type * as DateTime from "./DateTime.js"
|
||||
import * as Duration from "./Duration.js"
|
||||
import type { Effect } from "./Effect.js"
|
||||
import * as Either from "./Either.js"
|
||||
import type { LazyArg } from "./Function.js"
|
||||
import { constant, constTrue, dual, identity } from "./Function.js"
|
||||
import { isEffect } from "./internal/core.js"
|
||||
@@ -13,6 +12,7 @@ import * as effect from "./internal/effect.js"
|
||||
import { type Pipeable, pipeArguments } from "./Pipeable.js"
|
||||
import { hasProperty } from "./Predicate.js"
|
||||
import * as Pull from "./Pull.js"
|
||||
import * as Result from "./Result.js"
|
||||
import type { Contravariant, Covariant } from "./Types.js"
|
||||
|
||||
/**
|
||||
@@ -231,34 +231,34 @@ export const andThen: {
|
||||
self: Schedule<Output, Input, Error, Env>,
|
||||
other: Schedule<Output2, Input2, Error2, Env2>
|
||||
): Schedule<Output | Output2, Input & Input2, Error | Error2, Env | Env2> =>
|
||||
map(andThenEither(self, other), Either.merge))
|
||||
map(andThenResult(self, other), Result.merge))
|
||||
|
||||
/**
|
||||
* Returns a new `Schedule` that will first execute the left (i.e. `self`)
|
||||
* schedule to completion. Once the left schedule is complete, the right (i.e.
|
||||
* `other`) schedule will be executed to completion.
|
||||
*
|
||||
* The output of the resulting schedule is an `Either` where outputs of the
|
||||
* left schedule are emitted as `Either.Left<Output>` and outputs of the right
|
||||
* schedule are emitted as `Either.Right<Output>`.
|
||||
* The output of the resulting schedule is a `Result` where outputs of the
|
||||
* left schedule are emitted as `Result.Err<Output>` and outputs of the right
|
||||
* schedule are emitted as `Result.Ok<Output>`.
|
||||
*
|
||||
* @since 2.0.0
|
||||
* @category sequencing
|
||||
*/
|
||||
export const andThenEither: {
|
||||
export const andThenResult: {
|
||||
<Output2, Input2, Error2, Env2>(
|
||||
other: Schedule<Output2, Input2, Error2, Env2>
|
||||
): <Output, Input, Error, Env>(
|
||||
self: Schedule<Output, Input, Error, Env>
|
||||
) => Schedule<Either.Either<Output2, Output>, Input & Input2, Error | Error2, Env | Env2>
|
||||
) => Schedule<Result.Result<Output2, Output>, Input & Input2, Error | Error2, Env | Env2>
|
||||
<Output, Input, Error, Env, Output2, Input2, Error2, Env2>(
|
||||
self: Schedule<Output, Input, Error, Env>,
|
||||
other: Schedule<Output2, Input2, Error2, Env2>
|
||||
): Schedule<Either.Either<Output2, Output>, Input & Input2, Error | Error2, Env | Env2>
|
||||
): Schedule<Result.Result<Output2, Output>, Input & Input2, Error | Error2, Env | Env2>
|
||||
} = dual(2, <Output, Input, Error, Env, Output2, Input2, Error2, Env2>(
|
||||
self: Schedule<Output, Input, Error, Env>,
|
||||
other: Schedule<Output2, Input2, Error2, Env2>
|
||||
): Schedule<Either.Either<Output2, Output>, Input & Input2, Error | Error2, Env | Env2> =>
|
||||
): Schedule<Result.Result<Output2, Output>, Input & Input2, Error | Error2, Env | Env2> =>
|
||||
fromStep(effect.map(
|
||||
effect.zip(toStep(self), toStep(other)),
|
||||
([leftStep, rightStep]) => {
|
||||
@@ -268,20 +268,20 @@ export const andThenEither: {
|
||||
Output | Output2,
|
||||
Env | Env2
|
||||
> = leftStep
|
||||
let toEither: (output: Output | Output2) => Either.Either<Output2, Output> = Either.left as any
|
||||
let toResult: (output: Output | Output2) => Result.Result<Output2, Output> = Result.err as any
|
||||
return (now, input) =>
|
||||
Pull.matchEffect(currentStep(now, input), {
|
||||
onSuccess: ([output, duration]) =>
|
||||
effect.succeed<[Either.Either<Output2, Output>, Duration.Duration]>([toEither(output), duration]),
|
||||
effect.succeed<[Result.Result<Output2, Output>, Duration.Duration]>([toResult(output), duration]),
|
||||
onFailure: effect.failCause,
|
||||
onHalt: (output) =>
|
||||
effect.suspend(() => {
|
||||
const pull = effect.succeed<[Either.Either<Output2, Output>, Duration.Duration]>(
|
||||
[toEither(output), Duration.zero]
|
||||
const pull = effect.succeed<[Result.Result<Output2, Output>, Duration.Duration]>(
|
||||
[toResult(output), Duration.zero]
|
||||
)
|
||||
if (currentStep === leftStep) {
|
||||
currentStep = rightStep
|
||||
toEither = Either.right as any
|
||||
toResult = Result.ok as any
|
||||
}
|
||||
return pull
|
||||
})
|
||||
@@ -473,7 +473,7 @@ export const cron: {
|
||||
(expression: Cron.Cron): Schedule<Duration.Duration, unknown, Cron.CronParseError>
|
||||
(expression: string, tz?: string | DateTime.TimeZone): Schedule<Duration.Duration, unknown, Cron.CronParseError>
|
||||
} = (expression: string | Cron.Cron, tz?: string | DateTime.TimeZone) => {
|
||||
const parsed = Cron.isCron(expression) ? Either.right(expression) : Cron.parse(expression, tz)
|
||||
const parsed = Cron.isCron(expression) ? Result.ok(expression) : Cron.parse(expression, tz)
|
||||
return fromStep(effect.map(parsed.asEffect(), (cron) => (now, _) =>
|
||||
effect.sync(() => {
|
||||
const next = Cron.next(cron, now).getTime()
|
||||
|
||||
@@ -7,7 +7,7 @@ import { getBugErrorMessage } from "./internal/errors.js"
|
||||
import { isNullable, isObject } from "./Predicate.js"
|
||||
import type * as Types from "./Types.js"
|
||||
|
||||
/*
|
||||
/**
|
||||
* Copyright 2014 Thom Chiovoloni, released under the MIT license.
|
||||
*
|
||||
* A random number generator based on the basic implementation of the PCG algorithm,
|
||||
|
||||
@@ -157,11 +157,6 @@ export * as Duration from "./Duration.js"
|
||||
*/
|
||||
export * as Effect from "./Effect.js"
|
||||
|
||||
/**
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export * as Either from "./Either.js"
|
||||
|
||||
/**
|
||||
* This module provides encoding & decoding functionality for:
|
||||
*
|
||||
|
||||
@@ -3,7 +3,6 @@ import * as Clock from "../Clock.js"
|
||||
import type * as DateTime from "../DateTime.js"
|
||||
import * as Duration from "../Duration.js"
|
||||
import type * as Effect from "../Effect.js"
|
||||
import * as Either from "../Either.js"
|
||||
import * as Equal from "../Equal.js"
|
||||
import * as equivalence from "../Equivalence.js"
|
||||
import type { LazyArg } from "../Function.js"
|
||||
@@ -14,6 +13,7 @@ import * as Option from "../Option.js"
|
||||
import * as order from "../Order.js"
|
||||
import { pipeArguments } from "../Pipeable.js"
|
||||
import * as Predicate from "../Predicate.js"
|
||||
import * as Result from "../Result.js"
|
||||
import type { Mutable } from "../Types.js"
|
||||
import * as effect from "./effect.js"
|
||||
|
||||
@@ -455,16 +455,16 @@ export const distance: {
|
||||
} = dual(2, (self: DateTime.DateTime, other: DateTime.DateTime): number => toEpochMillis(other) - toEpochMillis(self))
|
||||
|
||||
/** @internal */
|
||||
export const distanceDurationEither: {
|
||||
(other: DateTime.DateTime): (self: DateTime.DateTime) => Either.Either<Duration.Duration, Duration.Duration>
|
||||
(self: DateTime.DateTime, other: DateTime.DateTime): Either.Either<Duration.Duration, Duration.Duration>
|
||||
export const distanceDurationResult: {
|
||||
(other: DateTime.DateTime): (self: DateTime.DateTime) => Result.Result<Duration.Duration, Duration.Duration>
|
||||
(self: DateTime.DateTime, other: DateTime.DateTime): Result.Result<Duration.Duration, Duration.Duration>
|
||||
} = dual(
|
||||
2,
|
||||
(self: DateTime.DateTime, other: DateTime.DateTime): Either.Either<Duration.Duration, Duration.Duration> => {
|
||||
(self: DateTime.DateTime, other: DateTime.DateTime): Result.Result<Duration.Duration, Duration.Duration> => {
|
||||
const diffMillis = distance(self, other)
|
||||
return diffMillis > 0
|
||||
? Either.right(Duration.millis(diffMillis))
|
||||
: Either.left(Duration.millis(-diffMillis))
|
||||
? Result.ok(Duration.millis(diffMillis))
|
||||
: Result.err(Duration.millis(-diffMillis))
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import type * as Console from "../Console.js"
|
||||
import * as Context from "../Context.js"
|
||||
import * as Duration from "../Duration.js"
|
||||
import type * as Effect from "../Effect.js"
|
||||
import * as Either from "../Either.js"
|
||||
import * as Equal from "../Equal.js"
|
||||
import type * as Exit from "../Exit.js"
|
||||
import type * as Fiber from "../Fiber.js"
|
||||
@@ -537,9 +536,6 @@ export const fromYieldable = <A, E, R>(yieldable: Effect.Yieldable<A, E, R>): Ef
|
||||
/** @internal */
|
||||
export const fromOption: <A>(option: Option.Option<A>) => Effect.Effect<A, Cause.NoSuchElementError> = fromYieldable
|
||||
|
||||
/** @internal */
|
||||
export const fromEither: <A, E>(either: Either.Either<A, E>) => Effect.Effect<A, E> = fromYieldable
|
||||
|
||||
/** @internal */
|
||||
export const fromResult: <A, E>(result: Result.Result<A, E>) => Effect.Effect<A, E> = fromYieldable
|
||||
|
||||
@@ -2069,11 +2065,6 @@ export const option = <A, E, R>(
|
||||
self: Effect.Effect<A, E, R>
|
||||
): Effect.Effect<Option.Option<A>, never, R> => match(self, { onFailure: Option.none, onSuccess: Option.some })
|
||||
|
||||
/** @internal */
|
||||
export const either = <A, E, R>(
|
||||
self: Effect.Effect<A, E, R>
|
||||
): Effect.Effect<Either.Either<A, E>, never, R> => match(self, { onFailure: Either.left, onSuccess: Either.right })
|
||||
|
||||
/** @internal */
|
||||
export const result = <A, E, R>(
|
||||
self: Effect.Effect<A, E, R>
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
/**
|
||||
* @since 2.0.0
|
||||
*/
|
||||
import type * as Either from "../Either.js"
|
||||
import * as Equal from "../Equal.js"
|
||||
import { dual } from "../Function.js"
|
||||
import * as Hash from "../Hash.js"
|
||||
import { toJSON } from "../Inspectable.js"
|
||||
import type { Option } from "../Option.js"
|
||||
import { hasProperty } from "../Predicate.js"
|
||||
import { exitFail, exitSucceed, PipeInspectableProto, YieldableProto } from "./core.js"
|
||||
import * as option from "./option.js"
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export const TypeId: Either.TypeId = Symbol.for(
|
||||
"effect/Either"
|
||||
) as Either.TypeId
|
||||
|
||||
const CommonProto = {
|
||||
[TypeId]: {
|
||||
_R: (_: never) => _
|
||||
},
|
||||
...PipeInspectableProto,
|
||||
...YieldableProto
|
||||
}
|
||||
|
||||
const RightProto = Object.assign(Object.create(CommonProto), {
|
||||
_tag: "Right",
|
||||
_op: "Right",
|
||||
[Equal.symbol]<L, R>(this: Either.Right<L, R>, that: unknown): boolean {
|
||||
return (
|
||||
isEither(that) && isRight(that) && Equal.equals(this.right, that.right)
|
||||
)
|
||||
},
|
||||
[Hash.symbol]<L, R>(this: Either.Right<L, R>) {
|
||||
return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.right))
|
||||
},
|
||||
toJSON<L, R>(this: Either.Right<L, R>) {
|
||||
return {
|
||||
_id: "Either",
|
||||
_tag: this._tag,
|
||||
right: toJSON(this.right)
|
||||
}
|
||||
},
|
||||
asEffect<L, R>(this: Either.Right<L, R>) {
|
||||
return exitSucceed(this.right)
|
||||
}
|
||||
})
|
||||
|
||||
const LeftProto = Object.assign(Object.create(CommonProto), {
|
||||
_tag: "Left",
|
||||
_op: "Left",
|
||||
[Equal.symbol]<L, R>(this: Either.Left<L, R>, that: unknown): boolean {
|
||||
return isEither(that) && isLeft(that) && Equal.equals(this.left, that.left)
|
||||
},
|
||||
[Hash.symbol]<L, R>(this: Either.Left<L, R>) {
|
||||
return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.left))
|
||||
},
|
||||
toJSON<E, A>(this: Either.Left<E, A>) {
|
||||
return {
|
||||
_id: "Either",
|
||||
_tag: this._tag,
|
||||
left: toJSON(this.left)
|
||||
}
|
||||
},
|
||||
asEffect<E, A>(this: Either.Left<E, A>) {
|
||||
return exitFail(this.left)
|
||||
}
|
||||
})
|
||||
|
||||
/** @internal */
|
||||
export const isEither = (
|
||||
input: unknown
|
||||
): input is Either.Either<unknown, unknown> => hasProperty(input, TypeId)
|
||||
|
||||
/** @internal */
|
||||
export const isLeft = <R, L>(
|
||||
ma: Either.Either<R, L>
|
||||
): ma is Either.Left<L, R> => ma._tag === "Left"
|
||||
|
||||
/** @internal */
|
||||
export const isRight = <R, L>(
|
||||
ma: Either.Either<R, L>
|
||||
): ma is Either.Right<L, R> => ma._tag === "Right"
|
||||
|
||||
/** @internal */
|
||||
export const left = <L>(left: L): Either.Either<never, L> => {
|
||||
const a = Object.create(LeftProto)
|
||||
a.left = left
|
||||
return a
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const right = <R>(right: R): Either.Either<R> => {
|
||||
const a = Object.create(RightProto)
|
||||
a.right = right
|
||||
return a
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const getLeft = <R, L>(self: Either.Either<R, L>): Option<L> =>
|
||||
isRight(self) ? option.none : option.some(self.left)
|
||||
|
||||
/** @internal */
|
||||
export const getRight = <R, L>(self: Either.Either<R, L>): Option<R> =>
|
||||
isLeft(self) ? option.none : option.some(self.right)
|
||||
|
||||
/** @internal */
|
||||
export const fromOption: {
|
||||
<L>(onNone: () => L): <R>(self: Option<R>) => Either.Either<R, L>
|
||||
<R, L>(self: Option<R>, onNone: () => L): Either.Either<R, L>
|
||||
} = dual(
|
||||
2,
|
||||
<R, L>(self: Option<R>, onNone: () => L): Either.Either<R, L> =>
|
||||
option.isNone(self) ? left(onNone()) : right(self.value)
|
||||
)
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as Either from "../../Either.js"
|
||||
import type * as Encoding from "../../Encoding.js"
|
||||
import * as Result from "../../Result.js"
|
||||
import { DecodeException } from "./common.js"
|
||||
|
||||
/** @internal */
|
||||
@@ -35,18 +35,18 @@ export const encode = (bytes: Uint8Array) => {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const decode = (str: string): Either.Either<Uint8Array, Encoding.DecodeException> => {
|
||||
export const decode = (str: string): Result.Result<Uint8Array, Encoding.DecodeException> => {
|
||||
const stripped = stripCrlf(str)
|
||||
const length = stripped.length
|
||||
if (length % 4 !== 0) {
|
||||
return Either.left(
|
||||
return Result.err(
|
||||
DecodeException(stripped, `Length must be a multiple of 4, but is ${length}`)
|
||||
)
|
||||
}
|
||||
|
||||
const index = stripped.indexOf("=")
|
||||
if (index !== -1 && ((index < length - 2) || (index === length - 2 && stripped[length - 1] !== "="))) {
|
||||
return Either.left(
|
||||
return Result.err(
|
||||
DecodeException(stripped, "Found a '=' character, but it is not at the end")
|
||||
)
|
||||
}
|
||||
@@ -65,9 +65,9 @@ export const decode = (str: string): Either.Either<Uint8Array, Encoding.DecodeEx
|
||||
result[j + 2] = buffer & 0xff
|
||||
}
|
||||
|
||||
return Either.right(result)
|
||||
return Result.ok(result)
|
||||
} catch (e) {
|
||||
return Either.left(
|
||||
return Result.err(
|
||||
DecodeException(stripped, e instanceof Error ? e.message : "Invalid input")
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as Either from "../../Either.js"
|
||||
import type * as Encoding from "../../Encoding.js"
|
||||
import * as Result from "../../Result.js"
|
||||
import * as Base64 from "./base64.js"
|
||||
import { DecodeException } from "./common.js"
|
||||
|
||||
@@ -8,17 +8,17 @@ export const encode = (data: Uint8Array) =>
|
||||
Base64.encode(data).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")
|
||||
|
||||
/** @internal */
|
||||
export const decode = (str: string): Either.Either<Uint8Array, Encoding.DecodeException> => {
|
||||
export const decode = (str: string): Result.Result<Uint8Array, Encoding.DecodeException> => {
|
||||
const stripped = Base64.stripCrlf(str)
|
||||
const length = stripped.length
|
||||
if (length % 4 === 1) {
|
||||
return Either.left(
|
||||
return Result.err(
|
||||
DecodeException(stripped, `Length should be a multiple of 4, but is ${length}`)
|
||||
)
|
||||
}
|
||||
|
||||
if (!/^[-_A-Z0-9]*?={0,2}$/i.test(stripped)) {
|
||||
return Either.left(DecodeException(stripped, "Invalid input"))
|
||||
return Result.err(DecodeException(stripped, "Invalid input"))
|
||||
}
|
||||
|
||||
// Some variants allow or require omitting the padding '=' signs
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as Either from "../../Either.js"
|
||||
import type * as Encoding from "../../Encoding.js"
|
||||
import * as Result from "../../Result.js"
|
||||
import { DecodeException } from "./common.js"
|
||||
|
||||
/** @internal */
|
||||
@@ -13,10 +13,10 @@ export const encode = (bytes: Uint8Array) => {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const decode = (str: string): Either.Either<Uint8Array, Encoding.DecodeException> => {
|
||||
export const decode = (str: string): Result.Result<Uint8Array, Encoding.DecodeException> => {
|
||||
const bytes = new TextEncoder().encode(str)
|
||||
if (bytes.length % 2 !== 0) {
|
||||
return Either.left(DecodeException(str, `Length must be a multiple of 2, but is ${bytes.length}`))
|
||||
return Result.err(DecodeException(str, `Length must be a multiple of 2, but is ${bytes.length}`))
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -28,9 +28,9 @@ export const decode = (str: string): Either.Either<Uint8Array, Encoding.DecodeEx
|
||||
result[i] = (a << 4) | b
|
||||
}
|
||||
|
||||
return Either.right(result)
|
||||
return Result.ok(result)
|
||||
} catch (e) {
|
||||
return Either.left(DecodeException(str, e instanceof Error ? e.message : "Invalid input"))
|
||||
return Result.err(DecodeException(str, e instanceof Error ? e.message : "Invalid input"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Either from "../Either.js"
|
||||
import { dual, identity } from "../Function.js"
|
||||
import type {
|
||||
Case,
|
||||
@@ -14,6 +13,7 @@ import type {
|
||||
import * as Option from "../Option.js"
|
||||
import { pipeArguments } from "../Pipeable.js"
|
||||
import type * as Predicate from "../Predicate.js"
|
||||
import * as Result from "../Result.js"
|
||||
import type { Unify } from "../Unify.js"
|
||||
|
||||
/** @internal */
|
||||
@@ -64,19 +64,19 @@ const ValueMatcherProto: Omit<
|
||||
this: ValueMatcher<any, any, any, any, any>,
|
||||
_case: Case
|
||||
): ValueMatcher<I, R, RA, A, Pr> {
|
||||
if (this.value._tag === "Right") {
|
||||
if (this.value._tag === "Ok") {
|
||||
return this
|
||||
}
|
||||
|
||||
if (_case._tag === "When" && _case.guard(this.provided) === true) {
|
||||
return makeValueMatcher(
|
||||
this.provided,
|
||||
Either.right(_case.evaluate(this.provided))
|
||||
Result.ok(_case.evaluate(this.provided))
|
||||
)
|
||||
} else if (_case._tag === "Not" && _case.guard(this.provided) === false) {
|
||||
return makeValueMatcher(
|
||||
this.provided,
|
||||
Either.right(_case.evaluate(this.provided))
|
||||
Result.ok(_case.evaluate(this.provided))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ const ValueMatcherProto: Omit<
|
||||
|
||||
function makeValueMatcher<I, R, RA, A, Pr>(
|
||||
provided: Pr,
|
||||
value: Either.Either<Pr, RA>
|
||||
value: Result.Result<Pr, RA>
|
||||
): ValueMatcher<I, R, RA, A, Pr> {
|
||||
const matcher = Object.create(ValueMatcherProto)
|
||||
matcher.provided = provided
|
||||
@@ -206,7 +206,7 @@ export const type = <I>(): Matcher<
|
||||
/** @internal */
|
||||
export const value = <const I>(
|
||||
i: I
|
||||
): Matcher<I, Types.Without<never>, I, never, I> => makeValueMatcher(i, Either.left(i))
|
||||
): Matcher<I, Types.Without<never>, I, never, I> => makeValueMatcher(i, Result.err(i))
|
||||
|
||||
/** @internal */
|
||||
export const valueTags: {
|
||||
@@ -543,17 +543,17 @@ export const orElse =
|
||||
<I, R, A, Pr>(self: Matcher<I, R, RA, A, Pr, Ret>): [Pr] extends [never] ? (input: I) => Unify<ReturnType<F> | A>
|
||||
: Unify<ReturnType<F> | A> =>
|
||||
{
|
||||
const result = either(self)
|
||||
const toResult = result(self)
|
||||
|
||||
if (Either.isEither(result)) {
|
||||
if (Result.isResult(toResult)) {
|
||||
// @ts-expect-error
|
||||
return result._tag === "Right" ? result.right : f(result.left)
|
||||
return toResult._tag === "Right" ? toResult.right : f(toResult.left)
|
||||
}
|
||||
|
||||
// @ts-expect-error
|
||||
return (input: I) => {
|
||||
const a = result(input)
|
||||
return a._tag === "Right" ? a.right : f(a.left)
|
||||
const a = toResult(input)
|
||||
return a._tag === "Ok" ? a.ok : f(a.err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,10 +566,10 @@ export const orElseAbsurd = <I, R, RA, A, Pr, Ret>(
|
||||
})(self)
|
||||
|
||||
/** @internal */
|
||||
export const either: <I, F, R, A, Pr, Ret>(
|
||||
export const result: <I, F, R, A, Pr, Ret>(
|
||||
self: Matcher<I, F, R, A, Pr, Ret>
|
||||
) => [Pr] extends [never] ? (input: I) => Either.Either<Unify<A>, R>
|
||||
: Either.Either<Unify<A>, R> = (<I, R, RA, A>(self: Matcher<I, R, RA, A, I>) => {
|
||||
) => [Pr] extends [never] ? (input: I) => Result.Result<Unify<A>, R>
|
||||
: Result.Result<Unify<A>, R> = (<I, R, RA, A>(self: Matcher<I, R, RA, A, I>) => {
|
||||
if (self._tag === "ValueMatcher") {
|
||||
return self.value
|
||||
}
|
||||
@@ -577,26 +577,26 @@ export const either: <I, F, R, A, Pr, Ret>(
|
||||
const len = self.cases.length
|
||||
if (len === 1) {
|
||||
const _case = self.cases[0]
|
||||
return (input: I): Either.Either<A, RA> => {
|
||||
return (input: I): Result.Result<A, RA> => {
|
||||
if (_case._tag === "When" && _case.guard(input) === true) {
|
||||
return Either.right(_case.evaluate(input))
|
||||
return Result.ok(_case.evaluate(input))
|
||||
} else if (_case._tag === "Not" && _case.guard(input) === false) {
|
||||
return Either.right(_case.evaluate(input))
|
||||
return Result.ok(_case.evaluate(input))
|
||||
}
|
||||
return Either.left(input as any)
|
||||
return Result.err(input as any)
|
||||
}
|
||||
}
|
||||
return (input: I): Either.Either<A, RA> => {
|
||||
return (input: I): Result.Result<A, RA> => {
|
||||
for (let i = 0; i < len; i++) {
|
||||
const _case = self.cases[i]
|
||||
if (_case._tag === "When" && _case.guard(input) === true) {
|
||||
return Either.right(_case.evaluate(input))
|
||||
return Result.ok(_case.evaluate(input))
|
||||
} else if (_case._tag === "Not" && _case.guard(input) === false) {
|
||||
return Either.right(_case.evaluate(input))
|
||||
return Result.ok(_case.evaluate(input))
|
||||
}
|
||||
}
|
||||
|
||||
return Either.left(input as any)
|
||||
return Result.err(input as any)
|
||||
}
|
||||
}) as any
|
||||
|
||||
@@ -605,17 +605,17 @@ export const option: <I, F, R, A, Pr, Ret>(
|
||||
self: Matcher<I, F, R, A, Pr, Ret>
|
||||
) => [Pr] extends [never] ? (input: I) => Option.Option<Unify<A>>
|
||||
: Option.Option<Unify<A>> = (<I, A>(self: Matcher<I, any, any, A, I>) => {
|
||||
const toEither = either(self)
|
||||
if (Either.isEither(toEither)) {
|
||||
return Either.match(toEither, {
|
||||
onLeft: () => Option.none(),
|
||||
onRight: Option.some
|
||||
const toResult = result(self)
|
||||
if (Result.isResult(toResult)) {
|
||||
return Result.match(toResult, {
|
||||
onErr: () => Option.none(),
|
||||
onOk: Option.some
|
||||
})
|
||||
}
|
||||
return (input: I): Option.Option<A> =>
|
||||
Either.match((toEither as any)(input), {
|
||||
onLeft: () => Option.none(),
|
||||
onRight: Option.some as any
|
||||
Result.match((toResult as any)(input), {
|
||||
onErr: () => Option.none(),
|
||||
onOk: Option.some as any
|
||||
})
|
||||
}) as any
|
||||
|
||||
@@ -627,11 +627,11 @@ export const exhaustive: <I, F, A, Pr, Ret>(
|
||||
) => [Pr] extends [never] ? (u: I) => Unify<A> : Unify<A> = (<I, F, A>(
|
||||
self: Matcher<I, F, never, A, I>
|
||||
) => {
|
||||
const toEither = either(self as any)
|
||||
const toResult = result(self as any)
|
||||
|
||||
if (Either.isEither(toEither)) {
|
||||
if (toEither._tag === "Right") {
|
||||
return toEither.right
|
||||
if (Result.isResult(toResult)) {
|
||||
if (toResult._tag === "Ok") {
|
||||
return toResult.ok
|
||||
}
|
||||
|
||||
throw new Error(getExhaustiveAbsurdErrorMessage)
|
||||
@@ -639,10 +639,10 @@ export const exhaustive: <I, F, A, Pr, Ret>(
|
||||
|
||||
return (u: I): A => {
|
||||
// @ts-expect-error
|
||||
const result = toEither(u)
|
||||
const result = toResult(u)
|
||||
|
||||
if (result._tag === "Right") {
|
||||
return result.right as any
|
||||
if (result._tag === "Ok") {
|
||||
return result.ok as any
|
||||
}
|
||||
|
||||
throw new Error(getExhaustiveAbsurdErrorMessage)
|
||||
|
||||
@@ -579,10 +579,10 @@ export const make = (
|
||||
Effect.withFiber((fiber) => {
|
||||
const controller = new AbortController()
|
||||
const urlResult = UrlParams.makeUrl(request.url, request.urlParams, request.hash)
|
||||
if (urlResult._tag === "Left") {
|
||||
return Effect.fail(new Error.RequestError({ request, reason: "InvalidUrl", cause: urlResult.left }))
|
||||
if (urlResult._tag === "Err") {
|
||||
return Effect.fail(new Error.RequestError({ request, reason: "InvalidUrl", cause: urlResult.err }))
|
||||
}
|
||||
const url = urlResult.right
|
||||
const url = urlResult.ok
|
||||
const tracerDisabled = fiber.getRef(Tracer.DisablePropagation) ||
|
||||
fiber.getRef(TracerDisabledWhen)(request)
|
||||
if (tracerDisabled) {
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import * as Arr from "../Array.js"
|
||||
import * as Either from "../Either.js"
|
||||
import { dual } from "../Function.js"
|
||||
import * as Option from "../Option.js"
|
||||
import * as Result from "../Result.js"
|
||||
|
||||
/**
|
||||
* @since 4.0.0
|
||||
@@ -197,7 +197,7 @@ export const remove: {
|
||||
* @since 4.0.0
|
||||
* @category conversions
|
||||
*/
|
||||
export const makeUrl = (url: string, params: UrlParams, hash: Option.Option<string>): Either.Either<URL, Error> => {
|
||||
export const makeUrl = (url: string, params: UrlParams, hash: Option.Option<string>): Result.Result<URL, Error> => {
|
||||
try {
|
||||
const urlInstance = new URL(url, baseUrl())
|
||||
for (let i = 0; i < params.length; i++) {
|
||||
@@ -209,9 +209,9 @@ export const makeUrl = (url: string, params: UrlParams, hash: Option.Option<stri
|
||||
if (hash._tag === "Some") {
|
||||
urlInstance.hash = hash.value
|
||||
}
|
||||
return Either.right(urlInstance)
|
||||
return Result.ok(urlInstance)
|
||||
} catch (e) {
|
||||
return Either.left(e as Error)
|
||||
return Result.err(e as Error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ import * as Cause from "effect/Cause"
|
||||
import * as Context from "effect/Context"
|
||||
import * as Data from "effect/Data"
|
||||
import * as Effect from "effect/Effect"
|
||||
import * as Either from "effect/Either"
|
||||
import * as Exit from "effect/Exit"
|
||||
import * as Fiber from "effect/Fiber"
|
||||
import { constFalse, constTrue, pipe } from "effect/Function"
|
||||
@@ -124,33 +123,6 @@ describe("Effect", () => {
|
||||
}))
|
||||
})
|
||||
|
||||
describe("fromEither", () => {
|
||||
it("from a right", () =>
|
||||
Either.right("A").pipe(
|
||||
Effect.fromEither,
|
||||
Effect.tap((_) => Effect.sync(() => assert.strictEqual(_, "A"))),
|
||||
Effect.runPromise
|
||||
))
|
||||
|
||||
it("from a left", () =>
|
||||
Either.left("error").asEffect().pipe(
|
||||
Effect.flip,
|
||||
Effect.tap((error) => Effect.sync(() => assert.strictEqual(error, "error"))),
|
||||
Effect.runPromise
|
||||
))
|
||||
|
||||
it.effect("yieldable", () =>
|
||||
Effect.gen(function*() {
|
||||
const result = yield* Either.right("A")
|
||||
assert.strictEqual(result, "A")
|
||||
|
||||
const error = yield* Effect.gen(function*() {
|
||||
yield* Either.left("error")
|
||||
}).pipe(Effect.flip)
|
||||
assert.strictEqual(error, "error")
|
||||
}))
|
||||
})
|
||||
|
||||
describe("fromResult", () => {
|
||||
it("from an ok", () =>
|
||||
Result.ok("A").pipe(
|
||||
|
||||
@@ -175,8 +175,8 @@ describe("Result", () => {
|
||||
})
|
||||
|
||||
it("getOrThrowWith", () => {
|
||||
strictEqual(pipe(Result.ok(1), Result.getOrThrowWith((e) => new Error(`Unexpected Left: ${e}`))), 1)
|
||||
throws(() => pipe(Result.err("e"), Result.getOrThrowWith((e) => new Error(`Unexpected Left: ${e}`))))
|
||||
strictEqual(pipe(Result.ok(1), Result.getOrThrowWith((e) => new Error(`Unexpected Err: ${e}`))), 1)
|
||||
throws(() => pipe(Result.err("e"), Result.getOrThrowWith((e) => new Error(`Unexpected Err: ${e}`))))
|
||||
})
|
||||
|
||||
it("getOrThrow", () => {
|
||||
|
||||
@@ -38,13 +38,13 @@ describe("Schedule", () => {
|
||||
})
|
||||
|
||||
describe("sequencing", () => {
|
||||
it.effect("andThenEither - executes schedules sequentially to completion", () =>
|
||||
it.effect("andThenResult - executes schedules sequentially to completion", () =>
|
||||
Effect.gen(function*() {
|
||||
const left = Schedule.fixed("500 millis").pipe(
|
||||
Schedule.while(({ recurrence }) => recurrence < 3)
|
||||
)
|
||||
const right = Schedule.fixed("1 second")
|
||||
const schedule = Schedule.andThenEither(left, right)
|
||||
const schedule = Schedule.andThenResult(left, right)
|
||||
const inputs = Array.makeBy(6, constUndefined)
|
||||
const outputs = yield* runDelays(schedule, inputs)
|
||||
expect(outputs).toEqual([
|
||||
|
||||
@@ -297,7 +297,7 @@ export const assertions = (asserts: {
|
||||
|
||||
result: {
|
||||
/**
|
||||
* Verifies that the either is a `Right` with the expected value.
|
||||
* Verifies that the Result is an `Ok` with the expected value.
|
||||
*/
|
||||
ok<const R, L>(result: Result.Result<R, L>, right: R) {
|
||||
if (Result.isOk(result)) {
|
||||
@@ -310,7 +310,7 @@ export const assertions = (asserts: {
|
||||
},
|
||||
|
||||
/**
|
||||
* Verifies that the either is a `Left` with the expected value.
|
||||
* Verifies that the Result is an `Err` with the expected value.
|
||||
*/
|
||||
err<R, const L>(result: Result.Result<R, L>, left: L) {
|
||||
if (Result.isErr(result)) {
|
||||
@@ -323,7 +323,7 @@ export const assertions = (asserts: {
|
||||
},
|
||||
|
||||
/**
|
||||
* Verifies that the either is a left with the expected value.
|
||||
* Verifies that the Result is an `Err` with the expected value.
|
||||
*/
|
||||
async fail<R>(encoded: Result.Result<R, SchemaIssue.Issue>, message: string) {
|
||||
const encodedWithMessage = Effect.gen(function*() {
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
* @since 0.21.0
|
||||
*/
|
||||
import type * as Cause from "effect/Cause"
|
||||
import * as Either from "effect/Either"
|
||||
import * as Equal from "effect/Equal"
|
||||
import * as Exit from "effect/Exit"
|
||||
import * as Option from "effect/Option"
|
||||
@@ -203,41 +202,11 @@ export function assertSome<A>(
|
||||
}
|
||||
|
||||
// ----------------------------
|
||||
// Either
|
||||
// Result
|
||||
// ----------------------------
|
||||
|
||||
/**
|
||||
* Asserts that `either` is `Left`.
|
||||
*
|
||||
* @since 0.21.0
|
||||
*/
|
||||
export function assertLeft<R, L>(
|
||||
either: Either.Either<R, L>,
|
||||
expected: L,
|
||||
..._: Array<never>
|
||||
): asserts either is Either.Left<L, never> {
|
||||
deepStrictEqual(either, Either.left(expected))
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that `either` is `Right`.
|
||||
*
|
||||
* @since 0.21.0
|
||||
*/
|
||||
export function assertRight<R, L>(
|
||||
either: Either.Either<R, L>,
|
||||
expected: R,
|
||||
..._: Array<never>
|
||||
): asserts either is Either.Right<never, R> {
|
||||
deepStrictEqual(either, Either.right(expected))
|
||||
}
|
||||
|
||||
// ----------------------------
|
||||
// Either
|
||||
// ----------------------------
|
||||
|
||||
/**
|
||||
* Asserts that `either` is `Left`.
|
||||
* Asserts that `result` is `Err`.
|
||||
*
|
||||
* @since 0.21.0
|
||||
*/
|
||||
@@ -250,7 +219,7 @@ export function assertOk<A, E>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that `either` is `Right`.
|
||||
* Asserts that `result` is `Err`.
|
||||
*
|
||||
* @since 0.21.0
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user