/** * @since 1.0.0 */ import type * as Data from "@effect/data/Data" import type { Either } from "@effect/data/Either" import * as Equal from "@effect/data/Equal" import * as Equivalence from "@effect/data/Equivalence" import type { LazyArg } from "@effect/data/Function" import { constNull, constUndefined, dual, identity } from "@effect/data/Function" import type { TypeLambda } from "@effect/data/HKT" import type { Inspectable } from "@effect/data/Inspectable" import * as either from "@effect/data/internal/Either" import * as option from "@effect/data/internal/Option" import * as N from "@effect/data/Number" import type { Order } from "@effect/data/Order" import * as order from "@effect/data/Order" import type { Pipeable } from "@effect/data/Pipeable" import type { Predicate, Refinement } from "@effect/data/Predicate" import type * as Unify from "@effect/data/Unify" import * as Gen from "@effect/data/UtilsGen" /** * @category models * @since 1.0.0 */ export type Option = None | Some /** * @category symbols * @since 1.0.0 */ export const TypeId = Symbol.for("@effect/data/Option") /** * @category symbols * @since 1.0.0 */ export type TypeId = typeof TypeId /** * @category models * @since 1.0.0 */ export interface None extends Data.Case, Pipeable, Inspectable { readonly _tag: "None" readonly [TypeId]: { readonly _A: (_: never) => A } [Unify.typeSymbol]?: unknown [Unify.unifySymbol]?: OptionUnify [Unify.blacklistSymbol]?: OptionUnifyBlacklist } /** * @category models * @since 1.0.0 */ export interface Some extends Data.Case, Pipeable, Inspectable { readonly _tag: "Some" readonly value: A readonly [TypeId]: { readonly _A: (_: never) => A } [Unify.typeSymbol]?: unknown [Unify.unifySymbol]?: OptionUnify [Unify.blacklistSymbol]?: OptionUnifyBlacklist } /** * @category models * @since 1.0.0 */ export interface OptionUnify { Option?: () => A[Unify.typeSymbol] extends Option | infer _ ? Option : never } /** * @category models * @since 1.0.0 */ export interface OptionUnifyBlacklist {} /** * @category type lambdas * @since 1.0.0 */ export interface OptionTypeLambda extends TypeLambda { readonly type: Option } /** * Creates a new `Option` that represents the absence of a value. * * @category constructors * @since 1.0.0 */ export const none = (): Option => option.none /** * Creates a new `Option` that wraps the given value. * * @param value - The value to wrap. * * @category constructors * @since 1.0.0 */ export const some: (value: A) => Option = option.some /** * Tests if a value is a `Option`. * * @param input - The value to check. * * @example * import { some, none, isOption } from '@effect/data/Option' * * assert.deepStrictEqual(isOption(some(1)), true) * assert.deepStrictEqual(isOption(none()), true) * assert.deepStrictEqual(isOption({}), false) * * @category guards * @since 1.0.0 */ export const isOption: (input: unknown) => input is Option = option.isOption /** * Determine if a `Option` is a `None`. * * @param self - The `Option` to check. * * @example * import { some, none, isNone } from '@effect/data/Option' * * assert.deepStrictEqual(isNone(some(1)), false) * assert.deepStrictEqual(isNone(none()), true) * * @category guards * @since 1.0.0 */ export const isNone: (self: Option) => self is None = option.isNone /** * Determine if a `Option` is a `Some`. * * @param self - The `Option` to check. * * @example * import { some, none, isSome } from '@effect/data/Option' * * assert.deepStrictEqual(isSome(some(1)), true) * assert.deepStrictEqual(isSome(none()), false) * * @category guards * @since 1.0.0 */ export const isSome: (self: Option) => self is Some = option.isSome /** * Matches the given `Option` and returns either the provided `onNone` value or the result of the provided `onSome` * function when passed the `Option`'s value. * * @param self - The `Option` to match * @param onNone - The value to be returned if the `Option` is `None` * @param onSome - The function to be called if the `Option` is `Some`, it will be passed the `Option`'s value and its result will be returned * * @example * import { some, none, match } from '@effect/data/Option' * import { pipe } from "@effect/data/Function" * * assert.deepStrictEqual( * pipe(some(1), match({ onNone: () => 'a none', onSome: (a) => `a some containing ${a}` })), * 'a some containing 1' * ) * * assert.deepStrictEqual( * pipe(none(), match({ onNone: () => 'a none', onSome: (a) => `a some containing ${a}` })), * 'a none' * ) * * @category pattern matching * @since 1.0.0 */ export const match: { (options: { readonly onNone: LazyArg readonly onSome: (a: A) => C }): (self: Option) => B | C (self: Option, options: { readonly onNone: LazyArg readonly onSome: (a: A) => C }): B | C } = dual( 2, (self: Option, { onNone, onSome }: { readonly onNone: LazyArg readonly onSome: (a: A) => C }): B | C => isNone(self) ? onNone() : onSome(self.value) ) /** * Returns a type guard from a `Option` returning function. * This function ensures that a type guard definition is type-safe. * * @example * import * as O from "@effect/data/Option" * * const parsePositive = (n: number): O.Option => * n > 0 ? O.some(n) : O.none() * * const isPositive = O.toRefinement(parsePositive) * * assert.deepStrictEqual(isPositive(1), true) * assert.deepStrictEqual(isPositive(-1), false) * * @category conversions * @since 1.0.0 */ export const toRefinement = (f: (a: A) => Option): (a: A) => a is B => (a: A): a is B => isSome(f(a)) /** * Converts an `Iterable` of values into an `Option`. Returns the first value of the `Iterable` wrapped in a `Some` * if the `Iterable` is not empty, otherwise returns `None`. * * @param collection - The `Iterable` to be converted to an `Option`. * * @example * import { fromIterable, some, none } from '@effect/data/Option' * * assert.deepStrictEqual(fromIterable([1, 2, 3]), some(1)) * assert.deepStrictEqual(fromIterable([]), none()) * * @category conversions * @since 1.0.0 */ export const fromIterable = (collection: Iterable): Option => { for (const a of collection) { return some(a) } return none() } /** * Converts a `Either` to an `Option` discarding the error. * * Alias of {@link fromEither}. * * @example * import * as O from "@effect/data/Option" * import * as E from "@effect/data/Either" * * assert.deepStrictEqual(O.getRight(E.right('ok')), O.some('ok')) * assert.deepStrictEqual(O.getRight(E.left('err')), O.none()) * * @category conversions * @since 1.0.0 */ export const getRight: (self: Either) => Option = either.getRight /** * Converts a `Either` to an `Option` discarding the value. * * @example * import * as O from "@effect/data/Option" * import * as E from "@effect/data/Either" * * assert.deepStrictEqual(O.getLeft(E.right("ok")), O.none()) * assert.deepStrictEqual(O.getLeft(E.left("a")), O.some("a")) * * @category conversions * @since 1.0.0 */ export const getLeft: (self: Either) => Option = either.getLeft /** * Returns the value of the `Option` if it is `Some`, otherwise returns `onNone` * * @param self - The `Option` to get the value of. * @param onNone - Function that returns the default value to return if the `Option` is `None`. * * @example * import { some, none, getOrElse } from '@effect/data/Option' * import { pipe } from "@effect/data/Function" * * assert.deepStrictEqual(pipe(some(1), getOrElse(() => 0)), 1) * assert.deepStrictEqual(pipe(none(), getOrElse(() => 0)), 0) * * @category getters * @since 1.0.0 */ export const getOrElse: { (onNone: LazyArg): (self: Option) => B | A (self: Option, onNone: LazyArg): A | B } = dual( 2, (self: Option, onNone: LazyArg): A | B => isNone(self) ? onNone() : self.value ) /** * Returns the provided `Option` `that` if `self` is `None`, otherwise returns `self`. * * @param self - The first `Option` to be checked. * @param that - The `Option` to return if `self` is `None`. * * @example * import * as O from "@effect/data/Option" * import { pipe } from "@effect/data/Function" * * assert.deepStrictEqual( * pipe( * O.none(), * O.orElse(() => O.none()) * ), * O.none() * ) * assert.deepStrictEqual( * pipe( * O.some('a'), * O.orElse(() => O.none()) * ), * O.some('a') * ) * assert.deepStrictEqual( * pipe( * O.none(), * O.orElse(() => O.some('b')) * ), * O.some('b') * ) * assert.deepStrictEqual( * pipe( * O.some('a'), * O.orElse(() => O.some('b')) * ), * O.some('a') * ) * * @category error handling * @since 1.0.0 */ export const orElse: { (that: LazyArg>): (self: Option) => Option (self: Option, that: LazyArg>): Option } = dual( 2, (self: Option, that: LazyArg>): Option => isNone(self) ? that() : self ) /** * Similar to `orElse`, but instead of returning a simple union, it returns an `Either` object, * which contains information about which of the two `Option`s has been chosen. * * This is useful when it's important to know whether the value was retrieved from the first `Option` or the second option. * * @param self - The first `Option` to be checked. * @param that - The second `Option` to be considered if the first `Option` is `None`. * * @category error handling * @since 1.0.0 */ export const orElseEither: { (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) ) /** * Given an `Iterable` collection of `Option`s, returns the first `Some` found in the collection. * * @param collection - An iterable collection of `Option` to be searched. * * @example * import * as O from "@effect/data/Option" * * assert.deepStrictEqual(O.firstSomeOf([O.none(), O.some(1), O.some(2)]), O.some(1)) * * @category error handling * @since 1.0.0 */ export const firstSomeOf = (collection: Iterable>): Option => { let out: Option = none() for (out of collection) { if (isSome(out)) { return out } } return out } /** * Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise * returns the value wrapped in a `Some`. * * @param nullableValue - The nullable value to be converted to an `Option`. * * @example * import * as O from "@effect/data/Option" * * assert.deepStrictEqual(O.fromNullable(undefined), O.none()) * assert.deepStrictEqual(O.fromNullable(null), O.none()) * assert.deepStrictEqual(O.fromNullable(1), O.some(1)) * * @category conversions * @since 1.0.0 */ export const fromNullable = ( nullableValue: A ): Option< NonNullable > => (nullableValue == null ? none() : some(nullableValue as NonNullable)) /** * This API is useful for lifting a function that returns `null` or `undefined` into the `Option` context. * * @example * import * as O from "@effect/data/Option" * * const parse = (s: string): number | undefined => { * const n = parseFloat(s) * return isNaN(n) ? undefined : n * } * * const parseOption = O.liftNullable(parse) * * assert.deepStrictEqual(parseOption('1'), O.some(1)) * assert.deepStrictEqual(parseOption('not a number'), O.none()) * * @category conversions * @since 1.0.0 */ export const liftNullable = , B>( f: (...a: A) => B | null | undefined ): (...a: A) => Option> => (...a) => fromNullable(f(...a)) /** * Returns the value of the `Option` if it is a `Some`, otherwise returns `null`. * * @param self - The `Option` to extract the value from. * * @example * import * as O from "@effect/data/Option" * * assert.deepStrictEqual(O.getOrNull(O.some(1)), 1) * assert.deepStrictEqual(O.getOrNull(O.none()), null) * * @category getters * @since 1.0.0 */ export const getOrNull: (self: Option) => A | null = getOrElse(constNull) /** * Returns the value of the `Option` if it is a `Some`, otherwise returns `undefined`. * * @param self - The `Option` to extract the value from. * * @example * import * as O from "@effect/data/Option" * * assert.deepStrictEqual(O.getOrUndefined(O.some(1)), 1) * assert.deepStrictEqual(O.getOrUndefined(O.none()), undefined) * * @category getters * @since 1.0.0 */ export const getOrUndefined: (self: Option) => A | undefined = getOrElse(constUndefined) /** * A utility function that lifts a function that throws exceptions into a function that returns an `Option`. * * This function is useful for any function that might throw an exception, allowing the developer to handle * the exception in a more functional way. * * @param f - the function that can throw exceptions. * * @example * import * as O from "@effect/data/Option" * * const parse = O.liftThrowable(JSON.parse) * * assert.deepStrictEqual(parse("1"), O.some(1)) * assert.deepStrictEqual(parse(""), O.none()) * * @category conversions * @since 1.0.0 */ export const liftThrowable = , B>( f: (...a: A) => B ): (...a: A) => Option => (...a) => { try { return some(f(...a)) } catch (e) { return none() } } /** * Extracts the value of an `Option` or throws if the `Option` is `None`. * * If a default error is sufficient for your use case and you don't need to configure the thrown error, see {@link getOrThrow}. * * @param self - The `Option` to extract the value from. * @param onNone - A function that will be called if the `Option` is `None`. It returns the error to be thrown. * * @example * import * as O from "@effect/data/Option" * * assert.deepStrictEqual( * O.getOrThrowWith(O.some(1), () => new Error('Unexpected None')), * 1 * ) * assert.throws(() => O.getOrThrowWith(O.none(), () => new Error('Unexpected None'))) * * @category conversions * @since 1.0.0 */ export const getOrThrowWith: { (onNone: () => unknown): (self: Option) => A (self: Option, onNone: () => unknown): A } = dual(2, (self: Option, onNone: () => unknown): A => { if (isSome(self)) { return self.value } throw onNone() }) /** * Extracts the value of an `Option` or throws if the `Option` is `None`. * * The thrown error is a default error. To configure the error thrown, see {@link getOrThrowWith}. * * @param self - The `Option` to extract the value from. * @throws `Error("getOrThrow called on a None")` * * @example * import * as O from "@effect/data/Option" * * assert.deepStrictEqual(O.getOrThrow(O.some(1)), 1) * assert.throws(() => O.getOrThrow(O.none())) * * @category conversions * @since 1.0.0 */ export const getOrThrow: (self: Option) => A = getOrThrowWith(() => new Error("getOrThrow called on a None")) /** * Maps the `Some` side of an `Option` value to a new `Option` value. * * @param self - An `Option` to map * @param f - The function to map over the value of the `Option` * * @category transforming * @since 1.0.0 */ export const map: { (f: (a: A) => B): (self: Option) => Option (self: Option, f: (a: A) => B): Option } = dual( 2, (self: Option, f: (a: A) => B): Option => isNone(self) ? none() : some(f(self.value)) ) /** * Maps the `Some` value of this `Option` to the specified constant value. * * @category transforming * @since 1.0.0 */ export const as: { (b: B): <_>(self: Option<_>) => Option } = dual(2, <_, B>(self: Option<_>, b: B): Option => map(self, () => b)) /** * Maps the `Some` value of this `Option` to the `void` constant value. * * This is useful when the value of the `Option` is not needed, but the presence or absence of the value is important. * * @category transforming * @since 1.0.0 */ export const asUnit: <_>(self: Option<_>) => Option = as(undefined) /** * @since 1.0.0 */ export const unit: Option = some(undefined) /** * Applies a function to the value of an `Option` and flattens the result, if the input is `Some`. * * @category transforming * @since 1.0.0 */ export const flatMap: { (f: (a: A) => Option): (self: Option) => Option (self: Option, f: (a: A) => Option): Option } = dual( 2, (self: Option, f: (a: A) => Option): Option => isNone(self) ? none() : f(self.value) ) /** * This is `flatMap` + `fromNullable`, useful when working with optional values. * * @example * import { some, none, flatMapNullable } from '@effect/data/Option' * import { pipe } from "@effect/data/Function" * * interface Employee { * company?: { * address?: { * street?: { * name?: string * } * } * } * } * * const employee1: Employee = { company: { address: { street: { name: 'high street' } } } } * * assert.deepStrictEqual( * pipe( * some(employee1), * flatMapNullable(employee => employee.company?.address?.street?.name), * ), * some('high street') * ) * * const employee2: Employee = { company: { address: { street: {} } } } * * assert.deepStrictEqual( * pipe( * some(employee2), * flatMapNullable(employee => employee.company?.address?.street?.name), * ), * none() * ) * * @category transforming * @since 1.0.0 */ export const flatMapNullable: { (f: (a: A) => B | null | undefined): (self: Option) => Option> (self: Option, f: (a: A) => B | null | undefined): Option> } = dual( 2, (self: Option, f: (a: A) => B | null | undefined): Option> => isNone(self) ? none() : fromNullable(f(self.value)) ) /** * @category transforming * @since 1.0.0 */ export const flatten: (self: Option>) => Option = flatMap(identity) /** * @category transforming * @since 1.0.0 */ export const zipRight: { (that: Option): <_>(self: Option<_>) => Option <_, B>(self: Option<_>, that: Option): Option } = dual(2, <_, B>(self: Option<_>, that: Option): Option => flatMap(self, () => that)) /** * @category transforming * @since 1.0.0 */ export const composeK: { (bfc: (b: B) => Option): (afb: (a: A) => Option) => (a: A) => Option (afb: (a: A) => Option, bfc: (b: B) => Option): (a: A) => Option } = dual(2, (afb: (a: A) => Option, bfc: (b: B) => Option) => (a: A): Option => flatMap(afb(a), bfc)) /** * Sequences the specified `that` `Option` but ignores its value. * * It is useful when we want to chain multiple operations, but only care about the result of `self`. * * @param that - The `Option` that will be ignored in the chain and discarded * @param self - The `Option` we care about * * @category transforming * @since 1.0.0 */ export const zipLeft: { <_>(that: Option<_>): (self: Option) => Option (self: Option, that: Option<_>): Option } = dual(2, (self: Option, that: Option<_>): Option => tap(self, () => that)) /** * Applies the provided function `f` to the value of the `Option` if it is `Some` and returns the original `Option` * unless `f` returns `None`, in which case it returns `None`. * * This function is useful for performing additional computations on the value of the input `Option` without affecting its value. * * @param f - Function to apply to the value of the `Option` if it is `Some` * @param self - The `Option` to apply the function to * * @example * import * as O from "@effect/data/Option" * * const getInteger = (n: number) => Number.isInteger(n) ? O.some(n) : O.none() * * assert.deepStrictEqual(O.tap(O.none(), getInteger), O.none()) * assert.deepStrictEqual(O.tap(O.some(1), getInteger), O.some(1)) * assert.deepStrictEqual(O.tap(O.some(1.14), getInteger), O.none()) * * @category transforming * @since 1.0.0 */ export const tap: { (f: (a: A) => Option<_>): (self: Option) => Option (self: Option, f: (a: A) => Option<_>): Option } = dual(2, (self: Option, f: (a: A) => Option<_>): Option => flatMap(self, (a) => map(f(a), () => a))) /** * @category combining * @since 1.0.0 */ export const product = (self: Option, that: Option): Option<[A, B]> => isSome(self) && isSome(that) ? some([self.value, that.value]) : none() /** * @category combining * @since 1.0.0 */ export const productMany = ( self: Option, collection: Iterable> ): Option<[A, ...Array]> => { if (isNone(self)) { return none() } const out: [A, ...Array] = [self.value] for (const o of collection) { if (isNone(o)) { return none() } out.push(o.value) } return some(out) } /** * Takes a structure of `Option`s and returns an `Option` of values with the same structure. * * - If a tuple is supplied, then the returned `Option` will contain a tuple with the same length. * - If a struct is supplied, then the returned `Option` will contain a struct with the same keys. * - If an iterable is supplied, then the returned `Option` will contain an array. * * @param fields - the struct of `Option`s to be sequenced. * * @example * import * as O from "@effect/data/Option" * * assert.deepStrictEqual(O.all([O.some(1), O.some(2)]), O.some([1, 2])) * assert.deepStrictEqual(O.all({ a: O.some(1), b: O.some("hello") }), O.some({ a: 1, b: "hello" })) * assert.deepStrictEqual(O.all({ a: O.some(1), b: O.none() }), O.none()) * * @category combining * @since 1.0.0 */ // @ts-expect-error export const all: > | Record>>( input: I ) => [I] extends [ReadonlyArray>] ? Option< { -readonly [K in keyof I]: [I[K]] extends [Option] ? A : never } > : [I] extends [Iterable>] ? Option> : Option<{ -readonly [K in keyof I]: [I[K]] extends [Option] ? A : never }> = ( input: Iterable> | Record> ): Option => { if (Symbol.iterator in input) { const out: Array> = [] for (const o of (input as Iterable>)) { if (isNone(o)) { return none() } out.push(o.value) } return some(out) } const out: Record = {} for (const key of Object.keys(input)) { const o = input[key] if (isNone(o)) { return none() } out[key] = o.value } return some(out) } /** * Zips two `Option` values together using a provided function, returning a new `Option` of the result. * * @param self - The left-hand side of the zip operation * @param that - The right-hand side of the zip operation * @param f - The function used to combine the values of the two `Option`s * * @example * import * as O from "@effect/data/Option" * * type Complex = [number, number] * * const complex = (real: number, imaginary: number): Complex => [real, imaginary] * * assert.deepStrictEqual(O.zipWith(O.none(), O.none(), complex), O.none()) * assert.deepStrictEqual(O.zipWith(O.some(1), O.none(), complex), O.none()) * assert.deepStrictEqual(O.zipWith(O.none(), O.some(1), complex), O.none()) * assert.deepStrictEqual(O.zipWith(O.some(1), O.some(2), complex), O.some([1, 2])) * * assert.deepStrictEqual(O.zipWith(O.some(1), complex)(O.some(2)), O.some([2, 1])) * * @category combining * @since 1.0.0 */ export const zipWith: { (that: Option, f: (a: A, b: B) => C): (self: Option) => Option (self: Option, that: Option, f: (a: A, b: B) => C): Option } = dual( 3, (self: Option, that: Option, f: (a: A, b: B) => C): Option => map(product(self, that), ([a, b]) => f(a, b)) ) /** * @category combining * @since 1.0.0 */ export const ap: { (that: Option): (self: Option<(a: A) => B>) => Option (self: Option<(a: A) => B>, that: Option): Option } = dual(2, (self: Option<(a: A) => B>, that: Option): Option => zipWith(self, that, (f, a) => f(a))) /** * Reduces an `Iterable` of `Option` to a single value of type `B`, elements that are `None` are ignored. * * @param self - The Iterable of `Option` to be reduced. * @param b - The initial value of the accumulator. * @param f - The reducing function that takes the current accumulator value and the unwrapped value of an `Option`. * * @example * import { some, none, reduceCompact } from '@effect/data/Option' * import { pipe } from "@effect/data/Function" * * const iterable = [some(1), none(), some(2), none()] * assert.deepStrictEqual(pipe(iterable, reduceCompact(0, (b, a) => b + a)), 3) * * @category folding * @since 1.0.0 */ export const reduceCompact: { (b: B, f: (b: B, a: A) => B): (self: Iterable>) => B (self: Iterable>, b: B, f: (b: B, a: A) => B): B } = dual( 3, (self: Iterable>, b: B, f: (b: B, a: A) => B): B => { let out: B = b for (const oa of self) { if (isSome(oa)) { out = f(out, oa.value) } } return out } ) /** * Transforms an `Option` into an `Array`. * If the input is `None`, an empty array is returned. * If the input is `Some`, the value is wrapped in an array. * * @param self - The `Option` to convert to an array. * * @example * import * as O from "@effect/data/Option" * * assert.deepStrictEqual(O.toArray(O.some(1)), [1]) * assert.deepStrictEqual(O.toArray(O.none()), []) * * @category conversions * @since 1.0.0 */ export const toArray = (self: Option): Array => isNone(self) ? [] : [self.value] /** * @category filtering * @since 1.0.0 */ export const partitionMap: { (f: (a: A) => Either): (self: Option) => [Option, Option] (self: Option, f: (a: A) => Either): [Option, Option] } = dual(2, ( self: Option, f: (a: A) => Either ): [Option, Option] => { if (isNone(self)) { return [none(), none()] } const e = f(self.value) return either.isLeft(e) ? [some(e.left), none()] : [none(), some(e.right)] }) /** * Maps over the value of an `Option` and filters out `None`s. * * Useful when in addition to filtering you also want to change the type of the `Option`. * * @param self - The `Option` to map over. * @param f - A function to apply to the value of the `Option`. * * @example * import * as O from "@effect/data/Option" * * const evenNumber = (n: number) => n % 2 === 0 ? O.some(n) : O.none() * * assert.deepStrictEqual(O.filterMap(O.none(), evenNumber), O.none()) * assert.deepStrictEqual(O.filterMap(O.some(3), evenNumber), O.none()) * assert.deepStrictEqual(O.filterMap(O.some(2), evenNumber), O.some(2)) * * @category filtering * @since 1.0.0 */ export const filterMap: { (f: (a: A) => Option): (self: Option) => Option (self: Option, f: (a: A) => Option): Option } = dual( 2, (self: Option, f: (a: A) => Option): Option => isNone(self) ? none() : f(self.value) ) /** * Filters an `Option` using a predicate. If the predicate is not satisfied or the `Option` is `None` returns `None`. * * If you need to change the type of the `Option` in addition to filtering, see `filterMap`. * * @param predicate - A predicate function to apply to the `Option` value. * @param fb - The `Option` to filter. * * @example * import * as O from "@effect/data/Option" * * // predicate * const isEven = (n: number) => n % 2 === 0 * * assert.deepStrictEqual(O.filter(O.none(), isEven), O.none()) * assert.deepStrictEqual(O.filter(O.some(3), isEven), O.none()) * assert.deepStrictEqual(O.filter(O.some(2), isEven), O.some(2)) * * // refinement * const isNumber = (v: unknown): v is number => typeof v === "number" * * assert.deepStrictEqual(O.filter(O.none(), isNumber), O.none()) * assert.deepStrictEqual(O.filter(O.some('hello'), isNumber), O.none()) * assert.deepStrictEqual(O.filter(O.some(2), isNumber), O.some(2)) * * @category filtering * @since 1.0.0 */ export const filter: { (refinement: (a: A) => a is B): (self: Option) => Option (predicate: (a: A) => boolean): (self: Option) => Option (self: Option, refinement: (a: A) => a is B): Option (self: Option, predicate: (a: A) => boolean): Option } = dual( 2, (self: Option, predicate: (a: A) => boolean): Option => filterMap(self, (b) => (predicate(b) ? option.some(b) : option.none)) ) /** * @example * import { none, some, getEquivalence } from '@effect/data/Option' * import * as N from '@effect/data/Number' * * const isEquivalent = getEquivalence(N.Equivalence) * assert.deepStrictEqual(isEquivalent(none(), none()), true) * assert.deepStrictEqual(isEquivalent(none(), some(1)), false) * assert.deepStrictEqual(isEquivalent(some(1), none()), false) * assert.deepStrictEqual(isEquivalent(some(1), some(2)), false) * assert.deepStrictEqual(isEquivalent(some(1), some(1)), true) * * @category equivalence * @since 1.0.0 */ export const getEquivalence = (isEquivalent: Equivalence.Equivalence): Equivalence.Equivalence> => Equivalence.make((x, y) => x === y || (isNone(x) ? isNone(y) : isNone(y) ? false : isEquivalent(x.value, y.value))) /** * The `Order` instance allows `Option` values to be compared with * `compare`, whenever there is an `Order` instance for * the type the `Option` contains. * * `None` is considered to be less than any `Some` value. * * @example * import { none, some, getOrder } from '@effect/data/Option' * import * as N from '@effect/data/Number' * import { pipe } from "@effect/data/Function" * * const O = getOrder(N.Order) * assert.deepStrictEqual(O(none(), none()), 0) * assert.deepStrictEqual(O(none(), some(1)), -1) * assert.deepStrictEqual(O(some(1), none()), 1) * assert.deepStrictEqual(O(some(1), some(2)), -1) * assert.deepStrictEqual(O(some(1), some(1)), 0) * * @category sorting * @since 1.0.0 */ export const getOrder = (O: Order): Order> => order.make((self, that) => isSome(self) ? (isSome(that) ? O(self.value, that.value) : 1) : -1) /** * Lifts a binary function into `Option`. * * @param f - The function to lift. * * @category lifting * @since 1.0.0 */ export const lift2 = (f: (a: A, b: B) => C): { (that: Option): (self: Option) => Option (self: Option, that: Option): Option } => dual(2, (self: Option, that: Option): Option => zipWith(self, that, f)) /** * Transforms a `Predicate` function into a `Some` of the input value if the predicate returns `true` or `None` * if the predicate returns `false`. * * @param predicate - A `Predicate` function that takes in a value of type `A` and returns a boolean. * * @example * import * as O from "@effect/data/Option" * * const getOption = O.liftPredicate((n: number) => n >= 0) * * assert.deepStrictEqual(getOption(-1), O.none()) * assert.deepStrictEqual(getOption(1), O.some(1)) * * @category lifting * @since 1.0.0 */ export const liftPredicate: { (refinement: Refinement): (c: C) => Option (predicate: Predicate): (b: B) => Option } = (predicate: Predicate) => (b: B) => predicate(b) ? some(b) : none() /** * Returns a function that checks if a `Option` contains a given value using a provided `isEquivalent` function. * * @param equivalent - An `Equivalence` instance to compare values of the `Option`. * @param self - The `Option` to apply the comparison to. * @param a - The value to compare against the `Option`. * * @example * import { some, none, containsWith } from '@effect/data/Option' * import { Equivalence } from '@effect/data/Number' * import { pipe } from "@effect/data/Function" * * assert.deepStrictEqual(pipe(some(2), containsWith(Equivalence)(2)), true) * assert.deepStrictEqual(pipe(some(1), containsWith(Equivalence)(2)), false) * assert.deepStrictEqual(pipe(none(), containsWith(Equivalence)(2)), false) * * @category elements * @since 1.0.0 */ export const containsWith = (isEquivalent: (self: A, that: A) => boolean): { (a: A): (self: Option) => boolean (self: Option, a: A): boolean } => dual(2, (self: Option, a: A): boolean => isNone(self) ? false : isEquivalent(self.value, a)) const _equivalence = Equal.equivalence() /** * Returns a function that checks if an `Option` contains a given value using the default `Equivalence`. * * @category elements * @since 1.0.0 */ export const contains: { (a: A): (self: Option) => boolean (self: Option, a: A): boolean } = containsWith(_equivalence) /** * Check if a value in an `Option` type meets a certain predicate. * * @param self - The `Option` to check. * @param predicate - The condition to check. * * @example * import { some, none, exists } from '@effect/data/Option' * import { pipe } from "@effect/data/Function" * * const isEven = (n: number) => n % 2 === 0 * * assert.deepStrictEqual(pipe(some(2), exists(isEven)), true) * assert.deepStrictEqual(pipe(some(1), exists(isEven)), false) * assert.deepStrictEqual(pipe(none(), exists(isEven)), false) * * @since 1.0.0 */ export const exists: { (predicate: Predicate): (self: Option) => boolean (self: Option, predicate: Predicate): boolean } = dual( 2, (self: Option, predicate: Predicate): boolean => isNone(self) ? false : predicate(self.value) ) // ------------------------------------------------------------------------------------- // math // ------------------------------------------------------------------------------------- /** * @category math * @since 1.0.0 */ export const sum: { (self: Option, that: Option): Option (that: Option): (self: Option) => Option } = lift2(N.sum) /** * @category math * @since 1.0.0 */ export const multiply: { (self: Option, that: Option): Option (that: Option): (self: Option) => Option } = lift2(N.multiply) /** * @category math * @since 1.0.0 */ export const subtract: { (self: Option, that: Option): Option (that: Option): (self: Option) => Option } = lift2(N.subtract) /** * @category math * @since 1.0.0 */ export const divide: { (self: Option, that: Option): Option (that: Option): (self: Option) => Option } = lift2(N.divide) /** * Sum all numbers in an iterable of `Option` ignoring the `None` values. * * @param self - The iterable of `Option` to be summed. * * @example * import { sumCompact, some, none } from '@effect/data/Option' * * const iterable = [some(2), none(), some(3), none()] * assert.deepStrictEqual(sumCompact(iterable), 5) * * @category math * @since 1.0.0 */ export const sumCompact = (self: Iterable>): number => { let out = 0 for (const oa of self) { if (isSome(oa)) { out += oa.value } } return out } /** * Multiply all numbers in an iterable of `Option` ignoring the `None` values. * * @param self - The iterable of `Option` to be multiplied. * * @example * import { multiplyCompact, some, none } from '@effect/data/Option' * * const iterable = [some(2), none(), some(3), none()] * assert.deepStrictEqual(multiplyCompact(iterable), 6) * * @category math * @since 1.0.0 */ export const multiplyCompact = (self: Iterable>): number => { let out = 1 for (const oa of self) { if (isSome(oa)) { const a: number = oa.value if (a === 0) { return 0 } out *= a } } return out } // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @category do notation * @since 1.0.0 */ export const bindTo: { (name: N): (self: Option) => Option<{ [K in N]: A }> (self: Option, name: N): Option<{ [K in N]: A }> } = dual( 2, (self: Option, name: N): Option<{ [K in N]: A }> => map(self, (a) => ({ [name]: a } as any)) ) const let_: { ( name: Exclude, f: (a: A) => B ): (self: Option) => Option<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }> ( self: Option, name: Exclude, f: (a: A) => B ): Option<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }> } = dual(3, ( self: Option, name: Exclude, f: (a: A) => B ): Option<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }> => map(self, (a) => Object.assign({}, a, { [name]: f(a) }) as any)) export { /** * @category do notation * @since 1.0.0 */ let_ as let } /** * @category do notation * @since 1.0.0 */ export const bind: { ( name: Exclude, f: (a: A) => Option ): (self: Option) => Option<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }> ( self: Option, name: Exclude, f: (a: A) => Option ): Option<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }> } = dual(3, ( self: Option, name: Exclude, f: (a: A) => Option ): Option<{ [K in keyof A | N]: K extends keyof A ? A[K] : B }> => flatMap(self, (a) => map(f(a), (b) => Object.assign({}, a, { [name]: b }) as any))) /** * @category do notation * @since 1.0.0 */ export const Do: Option<{}> = some({}) const adapter = Gen.adapter() /** * @category generators * @since 1.0.0 */ export const gen: Gen.Gen> = (f) => { const iterator = f(adapter) let state: IteratorYieldResult | IteratorReturnResult = iterator.next() if (state.done) { return some(void 0) } else { let current = state.value.value if (isNone(current)) { return current } while (!state.done) { state = iterator.next(current.value) if (!state.done) { current = state.value.value if (isNone(current)) { return current } } } return some(state.value) } }