diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 3a07917073..0f91802c55 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -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: { - (f: (a: A, i: number) => Either.Either): (self: Iterable) => [left: Array, right: Array] - (self: Iterable, f: (a: A, i: number) => Either.Either): [left: Array, right: Array] + (f: (a: A, i: number) => Result.Result): (self: Iterable) => [left: Array, right: Array] + (self: Iterable, f: (a: A, i: number) => Result.Result): [left: Array, right: Array] } = dual( 2, - (self: Iterable, f: (a: A, i: number) => Either.Either): [left: Array, right: Array] => { + (self: Iterable, f: (a: A, i: number) => Result.Result): [left: Array, right: Array] => { const left: Array = [] const right: Array = [] 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: >, X = any>( ) => Array>> = 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 = >>( +export const getErrs = >>( self: T -): Array>> => { +): Array>> => { const out: Array = [] 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 = >>( } /** - * 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 = >>( +export const getOks = >>( self: T -): Array>> => { +): Array>> => { const out: Array = [] 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: >>( +export const separate: >>( self: T -) => [Array>>, Array>>] = - partitionMap(identity) +) => [Array>>, Array>>] = 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 => - * isNaN(Number(s)) ? Either.left(new Error("Not a number")) : Either.right(Number(s)) + * const parseNumber = (s: string): Result.Result => + * 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 = , E, B>( - f: (...a: A) => Either.Either +export const liftResult = , E, B>( + f: (...a: A) => Result.Result ) => (...a: A): Array => { const e = f(...a) - return Either.isLeft(e) ? [] : [e.right] + return Result.isErr(e) ? [] : [e.ok] } /** diff --git a/packages/effect/src/Brand.ts b/packages/effect/src/Brand.ts index 1b597b9351..bb87aa0d3d 100644 --- a/packages/effect/src/Brand.ts +++ b/packages/effect/src/Brand.ts @@ -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): Option.Option /** - * Constructs a branded type from a value of type `A`, returning `Right` - * if the provided `A` is valid, `Left` otherwise. + * Constructs a branded type from a value of type `A`, returning `Ok` + * if the provided `A` is valid, `Err` otherwise. */ - either(args: Brand.Unbranded): Either.Either + result(args: Brand.Unbranded): Result.Result /** * 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>( (unbranded: Brand.Unbranded) => Brand.BrandErrors ] ): Brand.Constructor { - const either: (unbranded: Brand.Unbranded) => Either.Either = args.length === 2 ? - (unbranded) => args[0](unbranded) ? Either.right(unbranded as A) : Either.left(args[1](unbranded)) : + const result: (unbranded: Brand.Unbranded) => Result.Result = 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) => Either.getOrThrowWith(either(unbranded), identity), { + return Object.assign((unbranded: Brand.Unbranded) => Result.getOrThrowWith(result(unbranded), identity), { [RefinedConstructorsTypeId]: RefinedConstructorsTypeId, - option: (args: any) => Option.getRight(either(args)), - either, - is: (args: any): args is Brand.Unbranded & A => Either.isRight(either(args)) + option: (args: any) => Option.getOk(result(args)), + result, + is: (args: any): args is Brand.Unbranded & A => Result.isOk(result(args)) }) as any } @@ -273,7 +273,7 @@ export const nominal = >(): 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 => true }) } @@ -324,29 +324,29 @@ export const all: , ...Array extends infer X extends Brand ? X : Brand > => { - const either = (args: any): Either.Either => { - let result: Either.Either = Either.right(args) + const result = (args: any): Result.Result => { + let result: Result.Result = 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)) }) } diff --git a/packages/effect/src/Chunk.ts b/packages/effect/src/Chunk.ts index 02922d16c3..a39d3e0556 100644 --- a/packages/effect/src/Chunk.ts +++ b/packages/effect/src/Chunk.ts @@ -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: { - (f: (a: A) => Either): (self: Chunk) => [left: Chunk, right: Chunk] - (self: Chunk, f: (a: A) => Either): [left: Chunk, right: Chunk] -} = dual(2, (self: Chunk, f: (a: A) => Either): [left: Chunk, right: Chunk] => + (f: (a: A) => Result): (self: Chunk) => [left: Chunk, right: Chunk] + (self: Chunk, f: (a: A) => Result): [left: Chunk, right: Chunk] +} = dual(2, (self: Chunk, f: (a: A) => Result): [left: Chunk, right: Chunk] => 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 = (self: Chunk>): [Chunk, Chunk] => +export const separate = (self: Chunk>): [Chunk, Chunk] => pipe( RA.separate(toReadonlyArray(self)), ([l, r]) => [unsafeFromArray(l), unsafeFromArray(r)] diff --git a/packages/effect/src/Cron.ts b/packages/effect/src/Cron.ts index 5120e7e3f3..7e710af342 100644 --- a/packages/effect/src/Cron.ts +++ b/packages/effect/src/Cron.ts @@ -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 => { +export const parse = (cron: string, tz?: DateTime.TimeZone | string): Result.Result => { 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, CronParseError> => { +): Result.Result, CronParseError> => { const capacity = options.max - options.min + 1 const values = new Set() 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] => { diff --git a/packages/effect/src/DateTime.ts b/packages/effect/src/DateTime.ts index e1285fec88..655ca890d5 100644 --- a/packages/effect/src/DateTime.ts +++ b/packages/effect/src/DateTime.ts @@ -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 - (self: DateTime, other: DateTime): Either.Either -} = Internal.distanceDurationEither +export const distanceDurationResult: { + (other: DateTime): (self: DateTime) => Result.Result + (self: DateTime, other: DateTime): Result.Result +} = Internal.distanceDurationResult /** * Calulate the distance between two `DateTime` values. diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 896eaabbba..08fd9d85ce 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -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: ( // Conversions // ----------------------------------------------------------------------------- -/** - * @since 4.0.0 - * @category Conversions - */ -export const fromEither: (either: Either.Either) => Effect = 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 } = 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: ( - self: Effect -) => Effect, never, R> = internal.either - /** * Encapsulates both success and failure of an `Effect` into a `Result` type. * @@ -1504,7 +1464,7 @@ export const result: (self: Effect) => Effect = Left | Right - -/** - * @category symbols - * @since 2.0.0 - */ -export const TypeId: unique symbol = either.TypeId - -/** - * @category symbols - * @since 2.0.0 - */ -export type TypeId = typeof TypeId - -// TODO(4.0): flip the order of the type parameters -/** - * @category models - * @since 2.0.0 - */ -export interface Left extends Pipeable, Inspectable, Yieldable { - readonly _tag: "Left" - readonly _op: "Left" - readonly left: L - readonly [TypeId]: { - readonly _R: Covariant - readonly _L: Covariant - } - [Symbol.iterator](): EffectIterator> - [Unify.typeSymbol]?: unknown - [Unify.unifySymbol]?: EitherUnify - [Unify.ignoreSymbol]?: EitherUnifyIgnore -} - -// TODO(4.0): flip the order of the type parameters -/** - * @category models - * @since 2.0.0 - */ -export interface Right extends Pipeable, Inspectable, Yieldable { - readonly _tag: "Right" - readonly _op: "Right" - readonly right: R - readonly [TypeId]: { - readonly _R: Covariant - readonly _L: Covariant - } - [Symbol.iterator](): EffectIterator> - [Unify.typeSymbol]?: unknown - [Unify.unifySymbol]?: EitherUnify - [Unify.ignoreSymbol]?: EitherUnifyIgnore -} - -/** - * @category models - * @since 2.0.0 - */ -export interface EitherUnify { - Either?: () => A[Unify.typeSymbol] extends Either | infer _ ? Either : never -} - -/** - * @category models - * @since 2.0.0 - */ -export interface EitherUnifyIgnore {} - -/** - * @category type lambdas - * @since 2.0.0 - */ -export interface EitherTypeLambda extends TypeLambda { - readonly type: Either -} - -/** - * @since 2.0.0 - */ -export declare namespace Either { - /** - * @since 2.0.0 - * @category type-level - */ - export type Left> = [T] extends [Either] ? _E : never - /** - * @since 2.0.0 - * @category type-level - */ - export type Right> = [T] extends [Either] ? _A : never -} - -/** - * Constructs a new `Either` holding a `Right` value. This usually represents a successful value due to the right bias - * of this structure. - * - * @category constructors - * @since 2.0.0 - */ -export const right: (right: R) => Either = either.right - -const void_: Either = right(void 0) -export { - /** - * @category constructors - * @since 3.13.0 - */ - void_ as void -} - -/** - * Constructs a new `Either` holding a `Left` value. This usually represents a failure, due to the right-bias of this - * structure. - * - * @category constructors - * @since 2.0.0 - */ -export const left: (left: L) => Either = either.left - -/** - * Takes a lazy default and a nullable value, if the value is not nully (`null` or `undefined`), turn it into a `Right`, if the value is nully use - * the provided default as a `Left`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either } from "effect" - * - * assert.deepStrictEqual(Either.fromNullable(1, () => 'fallback'), Either.right(1)) - * assert.deepStrictEqual(Either.fromNullable(null, () => 'fallback'), Either.left('fallback')) - * ``` - * - * @category constructors - * @since 2.0.0 - */ -export const fromNullable: { - (onNullable: (right: R) => L): (self: R) => Either, L> - (self: R, onNullable: (right: R) => L): Either, L> -} = dual( - 2, - (self: R, onNullable: (right: R) => L): Either, L> => - self == null ? left(onNullable(self)) : right(self) -) - -/** - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either, Option } from "effect" - * - * assert.deepStrictEqual(Either.fromOption(Option.some(1), () => 'error'), Either.right(1)) - * assert.deepStrictEqual(Either.fromOption(Option.none(), () => 'error'), Either.left('error')) - * ``` - * - * @category constructors - * @since 2.0.0 - */ -export const fromOption: { - (onNone: () => L): (self: Option) => Either - (self: Option, onNone: () => L): Either -} = either.fromOption - -const try_: { - ( - options: { - readonly try: LazyArg - readonly catch: (error: unknown) => L - } - ): Either - (evaluate: LazyArg): Either -} = (( - evaluate: LazyArg | { - readonly try: LazyArg - readonly catch: (error: unknown) => L - } -) => { - if (isFunction(evaluate)) { - try { - return right(evaluate()) - } catch (e) { - return left(e) - } - } else { - try { - return right(evaluate.try()) - } catch (e) { - return left(evaluate.catch(e)) - } - } -}) as any - -export { - /** - * Imports a synchronous side-effect into a pure `Either` value, translating any - * thrown exceptions into typed failed eithers creating with `Either.left`. - * - * @category constructors - * @since 2.0.0 - */ - try_ as try -} - -/** - * Tests if a value is a `Either`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either } from "effect" - * - * assert.deepStrictEqual(Either.isEither(Either.right(1)), true) - * assert.deepStrictEqual(Either.isEither(Either.left("a")), true) - * assert.deepStrictEqual(Either.isEither({ right: 1 }), false) - * ``` - * - * @category guards - * @since 2.0.0 - */ -export const isEither: (input: unknown) => input is Either = either.isEither - -/** - * Determine if a `Either` is a `Left`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either } from "effect" - * - * assert.deepStrictEqual(Either.isLeft(Either.right(1)), false) - * assert.deepStrictEqual(Either.isLeft(Either.left("a")), true) - * ``` - * - * @category guards - * @since 2.0.0 - */ -export const isLeft: (self: Either) => self is Left = either.isLeft - -/** - * Determine if a `Either` is a `Right`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either } from "effect" - * - * assert.deepStrictEqual(Either.isRight(Either.right(1)), true) - * assert.deepStrictEqual(Either.isRight(Either.left("a")), false) - * ``` - * - * @category guards - * @since 2.0.0 - */ -export const isRight: (self: Either) => self is Right = either.isRight - -/** - * Converts a `Either` to an `Option` discarding the `Left`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either, Option } from "effect" - * - * assert.deepStrictEqual(Either.getRight(Either.right('ok')), Option.some('ok')) - * assert.deepStrictEqual(Either.getRight(Either.left('err')), Option.none()) - * ``` - * - * @category getters - * @since 2.0.0 - */ -export const getRight: (self: Either) => Option = either.getRight - -/** - * Converts a `Either` to an `Option` discarding the value. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either, Option } from "effect" - * - * assert.deepStrictEqual(Either.getLeft(Either.right('ok')), Option.none()) - * assert.deepStrictEqual(Either.getLeft(Either.left('err')), Option.some('err')) - * ``` - * - * @category getters - * @since 2.0.0 - */ -export const getLeft: (self: Either) => Option = either.getLeft - -/** - * @category equivalence - * @since 2.0.0 - */ -export const getEquivalence = ({ left, right }: { - right: Equivalence.Equivalence - left: Equivalence.Equivalence -}): Equivalence.Equivalence> => - Equivalence.make((x, y) => - isLeft(x) ? - isLeft(y) && left(x.left, y.left) : - isRight(y) && right(x.right, y.right) - ) - -/** - * @category mapping - * @since 2.0.0 - */ -export const mapBoth: { - (options: { - readonly onLeft: (left: L) => L2 - readonly onRight: (right: R) => R2 - }): (self: Either) => Either - (self: Either, options: { - readonly onLeft: (left: L) => L2 - readonly onRight: (right: R) => R2 - }): Either -} = dual( - 2, - (self: Either, { onLeft, onRight }: { - readonly onLeft: (left: L) => L2 - readonly onRight: (right: R) => R2 - }): Either => isLeft(self) ? left(onLeft(self.left)) : right(onRight(self.right)) -) - -/** - * Maps the `Left` side of an `Either` value to a new `Either` value. - * - * @category mapping - * @since 2.0.0 - */ -export const mapLeft: { - (f: (left: L) => L2): (self: Either) => Either - (self: Either, f: (left: L) => L2): Either -} = dual( - 2, - (self: Either, f: (left: L1) => L2): Either => - isLeft(self) ? left(f(self.left)) : right(self.right) -) - -/** - * Maps the `Right` side of an `Either` value to a new `Either` value. - * - * @category mapping - * @since 2.0.0 - */ -export const map: { - (f: (right: R) => R2): (self: Either) => Either - (self: Either, f: (right: R) => R2): Either -} = dual( - 2, - (self: Either, f: (right: R1) => R2): Either => - isRight(self) ? right(f(self.right)) : left(self.left) -) - -/** - * Takes two functions and an `Either` value, if the value is a `Left` the inner value is applied to the `onLeft function, - * if the value is a `Right` the inner value is applied to the `onRight` function. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { pipe, Either } from "effect" - * - * const onLeft = (strings: ReadonlyArray): string => `strings: ${strings.join(', ')}` - * - * const onRight = (value: number): string => `Ok: ${value}` - * - * assert.deepStrictEqual(pipe(Either.right(1), Either.match({ onLeft, onRight })), 'Ok: 1') - * assert.deepStrictEqual( - * pipe(Either.left(['string 1', 'string 2']), Either.match({ onLeft, onRight })), - * 'strings: string 1, string 2' - * ) - * ``` - * - * @category pattern matching - * @since 2.0.0 - */ -export const match: { - (options: { - readonly onLeft: (left: L) => B - readonly onRight: (right: R) => C - }): (self: Either) => B | C - (self: Either, options: { - readonly onLeft: (left: L) => B - readonly onRight: (right: R) => C - }): B | C -} = dual( - 2, - (self: Either, { onLeft, onRight }: { - readonly onLeft: (left: L) => B - readonly onRight: (right: R) => C - }): B | C => isLeft(self) ? onLeft(self.left) : onRight(self.right) -) - -/** - * Transforms a `Predicate` function into a `Right` of the input value if the predicate returns `true` - * or `Left` of the result of the provided function if the predicate returns false - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { pipe, Either } from "effect" - * - * const isPositive = (n: number): boolean => n > 0 - * - * assert.deepStrictEqual( - * pipe( - * 1, - * Either.liftPredicate(isPositive, n => `${n} is not positive`) - * ), - * Either.right(1) - * ) - * assert.deepStrictEqual( - * pipe( - * 0, - * Either.liftPredicate(isPositive, n => `${n} is not positive`) - * ), - * Either.left("0 is not positive") - * ) - * ``` - * - * @category lifting - * @since 3.4.0 - */ -export const liftPredicate: { - (refinement: Refinement, B>, orLeftWith: (a: NoInfer) => E): (a: A) => Either - ( - predicate: Predicate>, - orLeftWith: (a: NoInfer) => E - ): (a: A) => Either - ( - self: A, - refinement: Refinement, - orLeftWith: (a: A) => E - ): Either - ( - self: A, - predicate: Predicate>, - orLeftWith: (a: NoInfer) => E - ): Either -} = dual( - 3, - (a: A, predicate: Predicate, orLeftWith: (a: A) => E): Either => - predicate(a) ? right(a) : left(orLeftWith(a)) -) - -/** - * Filter the right value with the provided function. - * If the predicate fails, set the left value with the result of the provided function. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { pipe, Either } from "effect" - * - * const isPositive = (n: number): boolean => n > 0 - * - * assert.deepStrictEqual( - * pipe( - * Either.right(1), - * Either.filterOrLeft(isPositive, n => `${n} is not positive`) - * ), - * Either.right(1) - * ) - * assert.deepStrictEqual( - * pipe( - * Either.right(0), - * Either.filterOrLeft(isPositive, n => `${n} is not positive`) - * ), - * Either.left("0 is not positive") - * ) - * ``` - * - * @since 2.0.0 - * @category filtering & conditionals - */ -export const filterOrLeft: { - ( - refinement: Refinement, B>, - orLeftWith: (right: NoInfer) => L2 - ): (self: Either) => Either - ( - predicate: Predicate>, - orLeftWith: (right: NoInfer) => L2 - ): (self: Either) => Either - ( - self: Either, - refinement: Refinement, - orLeftWith: (right: R) => L2 - ): Either - (self: Either, predicate: Predicate, orLeftWith: (right: R) => E2): Either -} = dual(3, ( - self: Either, - predicate: Predicate, - orLeftWith: (right: R) => E2 -): Either => flatMap(self, (r) => predicate(r) ? right(r) : left(orLeftWith(r)))) - -/** - * @category getters - * @since 2.0.0 - */ -export const merge: (self: Either) => L | R = match({ - onLeft: identity, - onRight: identity -}) - -/** - * Returns the wrapped value if it's a `Right` or a default value if is a `Left`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either } from "effect" - * - * assert.deepStrictEqual(Either.getOrElse(Either.right(1), (error) => error + "!"), 1) - * assert.deepStrictEqual(Either.getOrElse(Either.left("not a number"), (error) => error + "!"), "not a number!") - * ``` - * - * @category getters - * @since 2.0.0 - */ -export const getOrElse: { - (onLeft: (left: L) => R2): (self: Either) => R2 | R - (self: Either, onLeft: (left: L) => R2): R | R2 -} = dual( - 2, - (self: Either, onLeft: (left: L) => B): R | B => isLeft(self) ? onLeft(self.left) : self.right -) - -/** - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either } from "effect" - * - * assert.deepStrictEqual(Either.getOrNull(Either.right(1)), 1) - * assert.deepStrictEqual(Either.getOrNull(Either.left("a")), null) - * ``` - * - * @category getters - * @since 2.0.0 - */ -export const getOrNull: (self: Either) => R | null = getOrElse(constNull) - -/** - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either } from "effect" - * - * assert.deepStrictEqual(Either.getOrUndefined(Either.right(1)), 1) - * assert.deepStrictEqual(Either.getOrUndefined(Either.left("a")), undefined) - * ``` - * - * @category getters - * @since 2.0.0 - */ -export const getOrUndefined: (self: Either) => R | undefined = getOrElse(constUndefined) - -/** - * Extracts the value of an `Either` or throws if the `Either` is `Left`. - * - * If a default error is sufficient for your use case and you don't need to configure the thrown error, see {@link getOrThrow}. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either } from "effect" - * - * assert.deepStrictEqual( - * Either.getOrThrowWith(Either.right(1), () => new Error('Unexpected Left')), - * 1 - * ) - * assert.throws(() => Either.getOrThrowWith(Either.left("error"), () => new Error('Unexpected Left'))) - * ``` - * - * @category getters - * @since 2.0.0 - */ -export const getOrThrowWith: { - (onLeft: (left: L) => unknown): (self: Either) => A - (self: Either, onLeft: (left: L) => unknown): R -} = dual(2, (self: Either, onLeft: (left: L) => unknown): R => { - if (isRight(self)) { - return self.right - } - throw onLeft(self.left) -}) - -// TODO(4.0): by default should throw `L` (i.e getOrThrowWith with the identity function) -/** - * Extracts the value of an `Either` or throws if the `Either` is `Left`. - * - * The thrown error is a default error. To configure the error thrown, see {@link getOrThrowWith}. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either } from "effect" - * - * assert.deepStrictEqual(Either.getOrThrow(Either.right(1)), 1) - * assert.throws(() => Either.getOrThrow(Either.left("error"))) - * ``` - * - * @throws `Error("getOrThrow called on a Left")` - * - * @category getters - * @since 2.0.0 - */ -export const getOrThrow: (self: Either) => R = getOrThrowWith(() => - new Error("getOrThrow called on a Left") -) - -/** - * Returns `self` if it is a `Right` or `that` otherwise. - * - * @category error handling - * @since 2.0.0 - */ -export const orElse: { - (that: (left: L) => Either): (self: Either) => Either - (self: Either, that: (left: L) => Either): Either -} = dual( - 2, - (self: Either, that: (left: L1) => Either): Either => - isLeft(self) ? that(self.left) : right(self.right) -) - -/** - * @category sequencing - * @since 2.0.0 - */ -export const flatMap: { - (f: (right: R) => Either): (self: Either) => Either - (self: Either, f: (right: R) => Either): Either -} = dual( - 2, - (self: Either, f: (right: R1) => Either): Either => - isLeft(self) ? left(self.left) : f(self.right) -) - -/** - * Executes a sequence of two `Either`s. The second `Either` can be dependent on the result of the first `Either`. - * - * @category sequencing - * @since 2.0.0 - */ -export const andThen: { - (f: (right: R) => Either): (self: Either) => Either - (f: Either): (self: Either) => Either - (f: (right: R) => R2): (self: Either) => Either - (right: NotFunction): (self: Either) => Either - (self: Either, f: (right: R) => Either): Either - (self: Either, f: Either): Either - (self: Either, f: (right: R) => R2): Either - (self: Either, f: NotFunction): Either -} = dual( - 2, - (self: Either, f: (right: R) => Either | Either): Either => - flatMap(self, (a) => { - const b = isFunction(f) ? f(a) : f - return isEither(b) ? b : right(b) - }) -) - -/** - * @category zipping - * @since 2.0.0 - */ -export const zipWith: { - ( - that: Either, - f: (right: R, right2: R2) => B - ): (self: Either) => Either - ( - self: Either, - that: Either, - f: (right: R, right2: R2) => B - ): Either -} = dual( - 3, - (self: Either, that: Either, f: (right: R, right2: R2) => B): Either => - flatMap(self, (r) => map(that, (r2) => f(r, r2))) -) - -/** - * @category combining - * @since 2.0.0 - */ -export const ap: { - (that: Either): (self: Either<(right: R) => R2, L>) => Either - (self: Either<(right: R) => R2, L>, that: Either): Either -} = dual( - 2, - (self: Either<(right: R) => R2, L>, that: Either): Either => - zipWith(self, that, (f, a) => f(a)) -) - -/** - * Takes a structure of `Either`s and returns an `Either` of values with the same structure. - * - * - If a tuple is supplied, then the returned `Either` will contain a tuple with the same length. - * - If a struct is supplied, then the returned `Either` will contain a struct with the same keys. - * - If an iterable is supplied, then the returned `Either` will contain an array. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either } from "effect" - * - * assert.deepStrictEqual(Either.all([Either.right(1), Either.right(2)]), Either.right([1, 2])) - * assert.deepStrictEqual(Either.all({ right: Either.right(1), b: Either.right("hello") }), Either.right({ right: 1, b: "hello" })) - * assert.deepStrictEqual(Either.all({ right: Either.right(1), b: Either.left("error") }), Either.left("error")) - * ``` - * - * @category combining - * @since 2.0.0 - */ -// @ts-expect-error -export const all: > | Record>>( - input: I -) => [I] extends [ReadonlyArray>] ? Either< - { -readonly [K in keyof I]: [I[K]] extends [Either] ? R : never }, - I[number] extends never ? never : [I[number]] extends [Either] ? L : never - > - : [I] extends [Iterable>] ? Either, L> - : Either< - { -readonly [K in keyof I]: [I[K]] extends [Either] ? R : never }, - I[keyof I] extends never ? never : [I[keyof I]] extends [Either] ? L : never - > = ( - input: Iterable> | Record> - ): Either => { - if (Symbol.iterator in input) { - const out: Array> = [] - for (const e of input) { - if (isLeft(e)) { - return e - } - out.push(e.right) - } - return right(out) - } - - const out: Record = {} - for (const key of Object.keys(input)) { - const e = input[key] - if (isLeft(e)) { - return e - } - out[key] = e.right - } - return right(out) - } - -/** - * Returns an `Either` that swaps the error/success cases. This allows you to - * use all methods on the error channel, possibly before flipping back. - * - * @since 2.0.0 - * @category mapping - */ -export const flip = (self: Either): Either => isLeft(self) ? right(self.left) : left(self.right) - -const adapter = Gen.adapter() - -/** - * @category generators - * @since 2.0.0 - */ -export const gen: Gen.Gen> = (...args) => { - const f = args.length === 1 ? args[0] : args[1].bind(args[0]) - const iterator = f(adapter) - let state: IteratorResult = iterator.next() - while (!state.done) { - const current = Gen.isGenKind(state.value) - ? state.value.value - : Gen.yieldWrapGet(state.value) - if (isLeft(current)) { - return current - } - state = iterator.next(current.right as never) - } - return right(state.value) as any -} - -// ------------------------------------------------------------------------------------- -// do notation -// ------------------------------------------------------------------------------------- - -/** - * The "do simulation" in Effect allows you to write code in a more declarative style, similar to the "do notation" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`. - * - * Here's how the do simulation works: - * - * 1. Start the do simulation using the `Do` value - * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Either` values - * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope - * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either, pipe } from "effect" - * - * const result = pipe( - * Either.Do, - * Either.bind("x", () => Either.right(2)), - * Either.bind("y", () => Either.right(3)), - * Either.let("sum", ({ x, y }) => x + y) - * ) - * assert.deepStrictEqual(result, Either.right({ x: 2, y: 3, sum: 5 })) - * ``` - * - * @see {@link bind} - * @see {@link bindTo} - * @see {@link let_ let} - * - * @category do notation - * @since 2.0.0 - */ -export const Do: Either<{}> = right({}) - -/** - * The "do simulation" in Effect allows you to write code in a more declarative style, similar to the "do notation" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`. - * - * Here's how the do simulation works: - * - * 1. Start the do simulation using the `Do` value - * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Either` values - * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope - * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either, pipe } from "effect" - * - * const result = pipe( - * Either.Do, - * Either.bind("x", () => Either.right(2)), - * Either.bind("y", () => Either.right(3)), - * Either.let("sum", ({ x, y }) => x + y) - * ) - * assert.deepStrictEqual(result, Either.right({ x: 2, y: 3, sum: 5 })) - * ``` - * - * @see {@link Do} - * @see {@link bindTo} - * @see {@link let_ let} - * - * @category do notation - * @since 2.0.0 - */ -export const bind: { - ( - name: Exclude, - f: (a: NoInfer) => Either - ): (self: Either) => Either<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, L1 | L2> - ( - self: Either, - name: Exclude, - f: (a: NoInfer) => Either - ): Either<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, L1 | L2> -} = doNotation.bind(map, flatMap) - -/** - * The "do simulation" in Effect allows you to write code in a more declarative style, similar to the "do notation" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`. - * - * Here's how the do simulation works: - * - * 1. Start the do simulation using the `Do` value - * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Either` values - * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope - * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either, pipe } from "effect" - * - * const result = pipe( - * Either.Do, - * Either.bind("x", () => Either.right(2)), - * Either.bind("y", () => Either.right(3)), - * Either.let("sum", ({ x, y }) => x + y) - * ) - * assert.deepStrictEqual(result, Either.right({ x: 2, y: 3, sum: 5 })) - * ``` - * - * @see {@link Do} - * @see {@link bind} - * @see {@link let_ let} - * - * @category do notation - * @since 2.0.0 - */ -export const bindTo: { - (name: N): (self: Either) => Either<{ [K in N]: R }, L> - (self: Either, name: N): Either<{ [K in N]: R }, L> -} = doNotation.bindTo(map) - -const let_: { - ( - name: Exclude, - f: (r: NoInfer) => B - ): (self: Either) => Either<{ [K in N | keyof R]: K extends keyof R ? R[K] : B }, L> - ( - self: Either, - name: Exclude, - f: (r: NoInfer) => B - ): Either<{ [K in N | keyof R]: K extends keyof R ? R[K] : B }, L> -} = doNotation.let_(map) - -export { - /** - * The "do simulation" in Effect allows you to write code in a more declarative style, similar to the "do notation" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`. - * - * Here's how the do simulation works: - * - * 1. Start the do simulation using the `Do` value - * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Either` values - * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope - * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Either, pipe } from "effect" - * - * const result = pipe( - * Either.Do, - * Either.bind("x", () => Either.right(2)), - * Either.bind("y", () => Either.right(3)), - * Either.let("sum", ({ x, y }) => x + y) - * ) - * assert.deepStrictEqual(result, Either.right({ x: 2, y: 3, sum: 5 })) - * ``` - * - * @see {@link Do} - * @see {@link bindTo} - * @see {@link bind} - * - * @category do notation - * @since 2.0.0 - */ - let_ as let -} - -/** - * Converts an `Option` of an `Either` into an `Either` of an `Option`. - * - * **Details** - * - * This function transforms an `Option>` into an - * `Either, E>`. If the `Option` is `None`, the resulting `Either` - * will be a `Right` with a `None` value. If the `Option` is `Some`, the - * inner `Either` will be executed, and its result wrapped in a `Some`. - * - * @example - * ```ts - * import { Effect, Either, Option } from "effect" - * - * // ┌─── Option> - * // ▼ - * const maybe = Option.some(Either.right(42)) - * - * // ┌─── Either, never, never> - * // ▼ - * const result = Either.transposeOption(maybe) - * ``` - * - * @since 3.14.0 - * @category Optional Wrapping & Unwrapping - */ -export const transposeOption = ( - self: Option> -): Either, E> => { - return option_.isNone(self) ? right(option_.none) : map(self.value, option_.some) -} diff --git a/packages/effect/src/Encoding.ts b/packages/effect/src/Encoding.ts index e0e8b61947..3856a85e12 100644 --- a/packages/effect/src/Encoding.ts +++ b/packages/effect/src/Encoding.ts @@ -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 => Base64.decode(str) +export const decodeBase64 = (str: string): Result.Result => 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 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 => Base64Url.decode(str) +export const decodeBase64Url = (str: string): Result.Result => 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 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 => Hex.decode(str) +export const decodeHex = (str: string): Result.Result => Hex.decode(str) /** * Decodes a hex encoded `string` into a UTF-8 `string`. @@ -86,7 +86,7 @@ export const decodeHex = (str: string): Either.Either Either.map(decodeHex(str), (_) => Common.decoder.decode(_)) +export const decodeHexString = (str: string) => Result.map(decodeHex(str), (_) => Common.decoder.decode(_)) /** * @since 2.0.0 diff --git a/packages/effect/src/Iterable.ts b/packages/effect/src/Iterable.ts index 420e1db2e5..8e42b0149e 100644 --- a/packages/effect/src/Iterable.ts +++ b/packages/effect/src/Iterable.ts @@ -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: (self: Iterable>) => Iterable = 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: (self: Iterable>) => Iterable = filterMap * @category filtering * @since 2.0.0 */ -export const getLefts = (self: Iterable>): Iterable => filterMap(self, E.getLeft) +export const getErrs = (self: Iterable>): Iterable => 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 = (self: Iterable>): Iterable => fil * @category filtering * @since 2.0.0 */ -export const getRights = (self: Iterable>): Iterable => filterMap(self, E.getRight) +export const getOks = (self: Iterable>): Iterable => filterMap(self, R.getOk) /** * @category filtering diff --git a/packages/effect/src/Match.ts b/packages/effect/src/Match.ts index b24e08e5df..f69fde5be8 100644 --- a/packages/effect/src/Match.ts +++ b/packages/effect/src/Match.ts @@ -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 } readonly provided: Provided - readonly value: Either.Either + readonly value: Result.Result add(_case: Case): ValueMatcher } @@ -710,7 +710,6 @@ export const discriminatorsExhaustive: ( * | { readonly _tag: "error"; readonly error: Error } * | { readonly _tag: "cancel" } * - * // Create a Matcher for Either * const match = Match.type().pipe( * // Match either "fetch" or "success" * Match.tag("fetch", "success", () => `Ok!`), @@ -1109,7 +1108,7 @@ export const orElse: Ret>( self: Matcher ) => [Pr] extends [never] ? (input: I) => Unify | A> : Unify | 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: ( ) => [Pr] extends [never] ? (input: I) => Unify : Unify = 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: ( * const getRole = Match.type().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: ( +export const result: ( self: Matcher -) => [Pr] extends [never] ? (input: I) => Either.Either, R> : Either.Either, R> = internal.either +) => [Pr] extends [never] ? (input: I) => Result.Result, R> : Result.Result, R> = internal.result /** * Wraps the match result in an `Option`, representing an optional match. diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index 322e07bb62..3f8dbdfeab 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -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 = (collection: Iterable): Option => { } /** - * 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: (self: Either) => Option = either.getRight +export const getOk: (self: Result) => Option = 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: (self: Either) => Option = either.getLeft +export const getErr: (self: Result) => Option = 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: { - (that: LazyArg>): (self: Option) => Option> - (self: Option, that: LazyArg>): Option> +export const orElseResult: { + (that: LazyArg>): (self: Option) => Option> + (self: Option, that: LazyArg>): Option> } = dual( 2, - (self: Option, that: LazyArg>): Option> => - isNone(self) ? map(that(), either.right) : map(self, either.left) + (self: Option, that: LazyArg>): Option> => + isNone(self) ? map(that(), result.ok) : map(self, result.err) ) /** @@ -1550,17 +1550,17 @@ export const toArray = (self: Option): Array => 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 = (self: Option): Array => isNone(self) ? [] : [se * @since 2.0.0 */ export const partitionMap: { - (f: (a: A) => Either): (self: Option) => [left: Option, right: Option] - (self: Option, f: (a: A) => Either): [left: Option, right: Option] + (f: (a: A) => Result): (self: Option) => [left: Option, right: Option] + (self: Option, f: (a: A) => Result): [left: Option, right: Option] } = dual(2, ( self: Option, - f: (a: A) => Either + f: (a: A) => Result ): [excluded: Option, satisfying: Option] => { 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? diff --git a/packages/effect/src/Record.ts b/packages/effect/src/Record.ts index 1f8596956a..040d1eae02 100644 --- a/packages/effect/src/Record.ts +++ b/packages/effect/src/Record.ts @@ -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: ( ) /** - * 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: ( * @category filtering * @since 2.0.0 */ -export const getLefts = ( - self: ReadonlyRecord> +export const getErrs = ( + self: ReadonlyRecord> ): Record, L> => { const out: Record = 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 = ( } /** - * 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 = ( * @category filtering * @since 2.0.0 */ -export const getRights = ( - self: ReadonlyRecord> +export const getOks = ( + self: ReadonlyRecord> ): Record => { const out: Record = 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 = ( * @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 = ( */ export const partitionMap: { ( - f: (a: A, key: K) => Either + f: (a: A, key: K) => Result ): ( self: ReadonlyRecord ) => [left: Record, B>, right: Record, C>] ( self: ReadonlyRecord, - f: (a: A, key: K) => Either + f: (a: A, key: K) => Result ): [left: Record, B>, right: Record, C>] } = dual( 2, ( self: ReadonlyRecord, - f: (a: A, key: K) => Either + f: (a: A, key: K) => Result ): [left: Record, B>, right: Record, C>] => { const left: Record = empty() const right: Record = 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: ( - self: ReadonlyRecord> + self: ReadonlyRecord> ) => [Record, A>, Record, B>] = partitionMap(identity) /** diff --git a/packages/effect/src/Result.ts b/packages/effect/src/Result.ts index 8fdadaf518..c480e9d62f 100644 --- a/packages/effect/src/Result.ts +++ b/packages/effect/src/Result.ts @@ -441,25 +441,25 @@ export const match: { * @since 4.0.0 */ export const liftPredicate: { - (refinement: Refinement, orLeftWith: (a: A) => E): (a: A) => Result + (refinement: Refinement, orErrWith: (a: A) => E): (a: A) => Result ( predicate: Predicate, - orLeftWith: (a: A) => E + orErrWith: (a: A) => E ): (a: B) => Result ( self: A, refinement: Refinement, - orLeftWith: (a: A) => E + orErrWith: (a: A) => E ): Result ( self: B, predicate: Predicate, - orLeftWith: (a: A) => E + orErrWith: (a: A) => E ): Result } = dual( 3, - (a: A, predicate: Predicate, orLeftWith: (a: A) => E): Result => - predicate(a) ? ok(a) : err(orLeftWith(a)) + (a: A, predicate: Predicate, orErrWith: (a: A) => E): Result => + predicate(a) ? ok(a) : err(orErrWith(a)) ) /** @@ -535,11 +535,11 @@ export const merge: (self: Result) => E | A = match({ onErr: identit * @since 4.0.0 */ export const getOrElse: { - (onLeft: (err: E) => A2): (self: Result) => A2 | A - (self: Result, onLeft: (err: E) => A2): A | A2 + (onErr: (err: E) => A2): (self: Result) => A2 | A + (self: Result, onErr: (err: E) => A2): A | A2 } = dual( 2, - (self: Result, onLeft: (err: E) => A2): A | A2 => isErr(self) ? onLeft(self.err) : self.ok + (self: Result, onErr: (err: E) => A2): A | A2 => isErr(self) ? onErr(self.err) : self.ok ) /** @@ -932,7 +932,7 @@ export { * * This function transforms an `Option>` into an * `Result, 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 diff --git a/packages/effect/src/Schedule.ts b/packages/effect/src/Schedule.ts index c49d3f1eb3..dd49e81e29 100644 --- a/packages/effect/src/Schedule.ts +++ b/packages/effect/src/Schedule.ts @@ -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, other: Schedule ): Schedule => - 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` and outputs of the right - * schedule are emitted as `Either.Right`. + * The output of the resulting schedule is a `Result` where outputs of the + * left schedule are emitted as `Result.Err` and outputs of the right + * schedule are emitted as `Result.Ok`. * * @since 2.0.0 * @category sequencing */ -export const andThenEither: { +export const andThenResult: { ( other: Schedule ): ( self: Schedule - ) => Schedule, Input & Input2, Error | Error2, Env | Env2> + ) => Schedule, Input & Input2, Error | Error2, Env | Env2> ( self: Schedule, other: Schedule - ): Schedule, Input & Input2, Error | Error2, Env | Env2> + ): Schedule, Input & Input2, Error | Error2, Env | Env2> } = dual(2, ( self: Schedule, other: Schedule -): Schedule, Input & Input2, Error | Error2, Env | Env2> => +): Schedule, 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 = Either.left as any + let toResult: (output: Output | Output2) => Result.Result = Result.err as any return (now, input) => Pull.matchEffect(currentStep(now, input), { onSuccess: ([output, duration]) => - effect.succeed<[Either.Either, Duration.Duration]>([toEither(output), duration]), + effect.succeed<[Result.Result, Duration.Duration]>([toResult(output), duration]), onFailure: effect.failCause, onHalt: (output) => effect.suspend(() => { - const pull = effect.succeed<[Either.Either, Duration.Duration]>( - [toEither(output), Duration.zero] + const pull = effect.succeed<[Result.Result, 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 (expression: string, tz?: string | DateTime.TimeZone): Schedule } = (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() diff --git a/packages/effect/src/Utils.ts b/packages/effect/src/Utils.ts index 85b7d83d9e..f918a2836d 100644 --- a/packages/effect/src/Utils.ts +++ b/packages/effect/src/Utils.ts @@ -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, diff --git a/packages/effect/src/index.ts b/packages/effect/src/index.ts index f9ae0c79a0..0e69005a5c 100644 --- a/packages/effect/src/index.ts +++ b/packages/effect/src/index.ts @@ -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: * diff --git a/packages/effect/src/internal/dateTime.ts b/packages/effect/src/internal/dateTime.ts index 99af97996c..572eafc673 100644 --- a/packages/effect/src/internal/dateTime.ts +++ b/packages/effect/src/internal/dateTime.ts @@ -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 - (self: DateTime.DateTime, other: DateTime.DateTime): Either.Either +export const distanceDurationResult: { + (other: DateTime.DateTime): (self: DateTime.DateTime) => Result.Result + (self: DateTime.DateTime, other: DateTime.DateTime): Result.Result } = dual( 2, - (self: DateTime.DateTime, other: DateTime.DateTime): Either.Either => { + (self: DateTime.DateTime, other: DateTime.DateTime): Result.Result => { 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)) } ) diff --git a/packages/effect/src/internal/effect.ts b/packages/effect/src/internal/effect.ts index 58a755bfa9..767c6b1261 100644 --- a/packages/effect/src/internal/effect.ts +++ b/packages/effect/src/internal/effect.ts @@ -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 = (yieldable: Effect.Yieldable): Ef /** @internal */ export const fromOption: (option: Option.Option) => Effect.Effect = fromYieldable -/** @internal */ -export const fromEither: (either: Either.Either) => Effect.Effect = fromYieldable - /** @internal */ export const fromResult: (result: Result.Result) => Effect.Effect = fromYieldable @@ -2069,11 +2065,6 @@ export const option = ( self: Effect.Effect ): Effect.Effect, never, R> => match(self, { onFailure: Option.none, onSuccess: Option.some }) -/** @internal */ -export const either = ( - self: Effect.Effect -): Effect.Effect, never, R> => match(self, { onFailure: Either.left, onSuccess: Either.right }) - /** @internal */ export const result = ( self: Effect.Effect diff --git a/packages/effect/src/internal/either.ts b/packages/effect/src/internal/either.ts deleted file mode 100644 index 9995bff968..0000000000 --- a/packages/effect/src/internal/either.ts +++ /dev/null @@ -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](this: Either.Right, that: unknown): boolean { - return ( - isEither(that) && isRight(that) && Equal.equals(this.right, that.right) - ) - }, - [Hash.symbol](this: Either.Right) { - return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.right)) - }, - toJSON(this: Either.Right) { - return { - _id: "Either", - _tag: this._tag, - right: toJSON(this.right) - } - }, - asEffect(this: Either.Right) { - return exitSucceed(this.right) - } -}) - -const LeftProto = Object.assign(Object.create(CommonProto), { - _tag: "Left", - _op: "Left", - [Equal.symbol](this: Either.Left, that: unknown): boolean { - return isEither(that) && isLeft(that) && Equal.equals(this.left, that.left) - }, - [Hash.symbol](this: Either.Left) { - return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.left)) - }, - toJSON(this: Either.Left) { - return { - _id: "Either", - _tag: this._tag, - left: toJSON(this.left) - } - }, - asEffect(this: Either.Left) { - return exitFail(this.left) - } -}) - -/** @internal */ -export const isEither = ( - input: unknown -): input is Either.Either => hasProperty(input, TypeId) - -/** @internal */ -export const isLeft = ( - ma: Either.Either -): ma is Either.Left => ma._tag === "Left" - -/** @internal */ -export const isRight = ( - ma: Either.Either -): ma is Either.Right => ma._tag === "Right" - -/** @internal */ -export const left = (left: L): Either.Either => { - const a = Object.create(LeftProto) - a.left = left - return a -} - -/** @internal */ -export const right = (right: R): Either.Either => { - const a = Object.create(RightProto) - a.right = right - return a -} - -/** @internal */ -export const getLeft = (self: Either.Either): Option => - isRight(self) ? option.none : option.some(self.left) - -/** @internal */ -export const getRight = (self: Either.Either): Option => - isLeft(self) ? option.none : option.some(self.right) - -/** @internal */ -export const fromOption: { - (onNone: () => L): (self: Option) => Either.Either - (self: Option, onNone: () => L): Either.Either -} = dual( - 2, - (self: Option, onNone: () => L): Either.Either => - option.isNone(self) ? left(onNone()) : right(self.value) -) diff --git a/packages/effect/src/internal/encoding/base64.ts b/packages/effect/src/internal/encoding/base64.ts index e23d0f6949..1cfdf07685 100644 --- a/packages/effect/src/internal/encoding/base64.ts +++ b/packages/effect/src/internal/encoding/base64.ts @@ -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 => { +export const decode = (str: string): Result.Result => { 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 Base64.encode(data).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") /** @internal */ -export const decode = (str: string): Either.Either => { +export const decode = (str: string): Result.Result => { 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 diff --git a/packages/effect/src/internal/encoding/hex.ts b/packages/effect/src/internal/encoding/hex.ts index a46d71202c..af54ea3467 100644 --- a/packages/effect/src/internal/encoding/hex.ts +++ b/packages/effect/src/internal/encoding/hex.ts @@ -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 => { +export const decode = (str: string): Result.Result => { 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, _case: Case ): ValueMatcher { - 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( provided: Pr, - value: Either.Either + value: Result.Result ): ValueMatcher { const matcher = Object.create(ValueMatcherProto) matcher.provided = provided @@ -206,7 +206,7 @@ export const type = (): Matcher< /** @internal */ export const value = ( i: I -): Matcher, I, never, I> => makeValueMatcher(i, Either.left(i)) +): Matcher, I, never, I> => makeValueMatcher(i, Result.err(i)) /** @internal */ export const valueTags: { @@ -543,17 +543,17 @@ export const orElse = (self: Matcher): [Pr] extends [never] ? (input: I) => Unify | A> : Unify | 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 = ( })(self) /** @internal */ -export const either: ( +export const result: ( self: Matcher -) => [Pr] extends [never] ? (input: I) => Either.Either, R> - : Either.Either, R> = ((self: Matcher) => { +) => [Pr] extends [never] ? (input: I) => Result.Result, R> + : Result.Result, R> = ((self: Matcher) => { if (self._tag === "ValueMatcher") { return self.value } @@ -577,26 +577,26 @@ export const either: ( const len = self.cases.length if (len === 1) { const _case = self.cases[0] - return (input: I): Either.Either => { + return (input: I): Result.Result => { 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 => { + return (input: I): Result.Result => { 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: ( self: Matcher ) => [Pr] extends [never] ? (input: I) => Option.Option> : Option.Option> = ((self: Matcher) => { - 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 => - 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: ( ) => [Pr] extends [never] ? (u: I) => Unify : Unify = (( self: Matcher ) => { - 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: ( 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) diff --git a/packages/effect/src/unstable/HttpClient.ts b/packages/effect/src/unstable/HttpClient.ts index 12eec22cd8..744a31811b 100644 --- a/packages/effect/src/unstable/HttpClient.ts +++ b/packages/effect/src/unstable/HttpClient.ts @@ -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) { diff --git a/packages/effect/src/unstable/UrlParams.ts b/packages/effect/src/unstable/UrlParams.ts index a50f5ae7b8..85a8ad5052 100644 --- a/packages/effect/src/unstable/UrlParams.ts +++ b/packages/effect/src/unstable/UrlParams.ts @@ -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): Either.Either => { +export const makeUrl = (url: string, params: UrlParams, hash: Option.Option): Result.Result => { 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 { })) }) - 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( diff --git a/packages/effect/test/Result.test.ts b/packages/effect/test/Result.test.ts index 2521f46e8a..d380830baf 100644 --- a/packages/effect/test/Result.test.ts +++ b/packages/effect/test/Result.test.ts @@ -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", () => { diff --git a/packages/effect/test/Schedule.test.ts b/packages/effect/test/Schedule.test.ts index c3bd195214..497924b1a5 100644 --- a/packages/effect/test/Schedule.test.ts +++ b/packages/effect/test/Schedule.test.ts @@ -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([ diff --git a/packages/effect/test/SchemaTest.ts b/packages/effect/test/SchemaTest.ts index fed5e68eca..3fc2a3cf8d 100644 --- a/packages/effect/test/SchemaTest.ts +++ b/packages/effect/test/SchemaTest.ts @@ -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(result: Result.Result, 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(result: Result.Result, 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(encoded: Result.Result, message: string) { const encodedWithMessage = Effect.gen(function*() { diff --git a/packages/vitest/src/utils.ts b/packages/vitest/src/utils.ts index 105d59b83c..25445baf20 100644 --- a/packages/vitest/src/utils.ts +++ b/packages/vitest/src/utils.ts @@ -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( } // ---------------------------- -// Either +// Result // ---------------------------- /** - * Asserts that `either` is `Left`. - * - * @since 0.21.0 - */ -export function assertLeft( - either: Either.Either, - expected: L, - ..._: Array -): asserts either is Either.Left { - deepStrictEqual(either, Either.left(expected)) -} - -/** - * Asserts that `either` is `Right`. - * - * @since 0.21.0 - */ -export function assertRight( - either: Either.Either, - expected: R, - ..._: Array -): asserts either is Either.Right { - 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( } /** - * Asserts that `either` is `Right`. + * Asserts that `result` is `Err`. * * @since 0.21.0 */