Skip to content

Instantly share code, notes, and snippets.

@mceachen
Created October 28, 2019 05:53
Show Gist options
  • Save mceachen/75598510275865b8cf88bb2ef804cd07 to your computer and use it in GitHub Desktop.
Save mceachen/75598510275865b8cf88bb2ef804cd07 to your computer and use it in GitHub Desktop.
TypeScript implementation of Optional/Some/None

MIT License

Copyright (c) 2016-2019 Matthew McEachen

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// SEE LICENSE
import { isFunction } from "./ObjectType"
export type Maybe<T> = T | undefined
export type MaybeNull<T> = Maybe<T> | null | void
export function map<T, U>(obj: MaybeNull<T>, f: (t: T) => U): Maybe<U> {
return obj == null ? undefined : f(obj)
}
export function map2<T1, T2, U>(
t1: MaybeNull<T1>,
t2: MaybeNull<T2>,
f: (t1: T1, t2: T2) => U
): Maybe<U> {
return t1 == null || t2 == null ? undefined : f(t1, t2)
}
export function orElse<T>(obj: MaybeNull<T>, defaultValue: T | (() => T)): T {
return obj != null
? obj
: isFunction(defaultValue)
? defaultValue()
: defaultValue
}
export function mapOr<T, U>(
obj: MaybeNull<T>,
f: (t: T) => U,
orElseF: () => U
): U {
return obj == null ? orElseF() : f(obj)
}
// https://www.typescriptlang.org/docs/handbook/advanced-types.html#predefined-conditional-types
export type Diff<T, U> = T extends U ? never : T
export type Unpick<T, U> = { [P in keyof T]: P extends U ? never : T[P] }
export type Defined<T> = Diff<T, null | undefined | void>
/**
* @return true iff all `objects` are not `null` or `undefined`
*/
export function defined<T>(object: T): object is Defined<T> {
return object != null
}
export function allDefined<T>(arr: T[]): arr is Defined<T>[] {
return arr != null && arr.every(defined)
}
export function firstDefined<T>(...objects: MaybeNull<T>[]): Maybe<T> {
return objects.find(defined)
}
export function denull<T>(t: T | undefined | null): T | undefined {
return t == null ? undefined : t
}
export type MaybeValued<T> = { [P in keyof T]: Maybe<T[P]> }
export type NullValued<T> = { [P in keyof T]: null | undefined }
export type ReqValued<T> = { [P in keyof T]: NonNullable<T[P]> }
// Async
export type PromiseMaybe<T> = Promise<Maybe<T>>
export type PromiseMaybeNull<T> = Promise<MaybeNull<T>>
export type MaybePromiseMaybe<T> = Maybe<Promise<Maybe<T>>>
export type MaybeNullPromiseMaybeNull<T> = MaybeNull<Promise<MaybeNull<T>>>
// SEE LICENSE
import { Maybe, MaybeNull } from "./Maybe"
// Scala got a Some things right.
// HUR HUR I AM HILLLARIOUS
// "Opt" instead of "Option" due to Option being an html entity already
export type MaybeOpt<T> = Opt<T> | MaybeNull<T>
/**
* @see http://www.scala-lang.org/api/current/scala/Option.html
*/
export interface Opt<A> {
/**
* @return true if the option is an instance of Some, false otherwise
*/
isDefined: boolean
/**
* @return true if the option is None, false otherwise
*/
isEmpty: boolean
/**
* @return the option's value.
*/
get(): Maybe<A>
/**
* @return true if this option is nonempty and the predicate `p` returns true
* when applied to this Option's value.
*/
exists(p: (a: A) => boolean): boolean
/**
* @return a `Some` containing the result of applying `f` to this `Option`'s value
* if this `Option` is nonempty.
*/
map<B>(f: (a: A) => B): Opt<B>
/**
* @return the result of applying `f` to this `Option`'s value if this
* `Option` is nonempty. By supporting `undefined` or `B`, we make caller's
* lives a little easier--we'll wrap the result in an `Option` for you.
*/
flatMap<B>(f: (a: A) => MaybeOpt<B>): Opt<B>
/**
* @return this `Option` if it is both nonempty
* and applying the predicate `p` to this `Option`'s value returns true.
*/
filter(p: (a: A) => boolean): Opt<A>
/**
* Apply the given procedure `f` to the `Option`'s value
* if this `Option` is nonempty.
* @return this (for fluent or chaining calls)
*/
forEach(f: (a: A) => void): Opt<A>
/**
* @return this `Option`'s value if this `Option` is nonempty,
* otherwise return the result of evaluating `f`.
*/
getOrElse(f: () => A): A
/**
* @return this `Option`'s value if this `Option` is nonempty,
* otherwise return the result of evaluating `f`.
*/
orElse(f: () => MaybeOpt<A>): Opt<A>
/**
* @param f will only be invoked if both `this` and `b` are defined
*/
zip1<B, T>(b: MaybeOpt<B>, f: (a: A, b: B) => MaybeOpt<T>): Opt<T>
zip2<B, C, T>(
b: MaybeOpt<B>,
c: MaybeOpt<C>,
f: (a: A, b: B, c: C) => MaybeOpt<T>
): Opt<T>
zip3<B, C, D, T>(
b: MaybeOpt<B>,
c: MaybeOpt<C>,
d: MaybeOpt<D>,
f: (a: A, b: B, c: C, d: D) => MaybeOpt<T>
): Opt<T>
}
namespace NoneImpl {
export const isDefined = false
export const isEmpty = true
export function get(): any {
return
}
export const exists = () => false
const noop = () => NoneImpl
export const map = noop
export const flatMap = noop
export const filter = noop
export const forEach = noop
export function getOrElse<A>(f: () => A): A {
return f()
}
export function orElse<A>(f: () => MaybeOpt<A>): Opt<A> {
return Opt(f())
}
export const zip1 = noop
export const zip2 = noop
export const zip3 = noop
}
export const None: Opt<any> = NoneImpl
export class Some<A> implements Opt<A> {
readonly isDefined = true
readonly isEmpty = false
constructor(private readonly a: A) {}
get(): A {
return this.a
}
exists(f: (a: A) => boolean): boolean {
return f(this.a)
}
map<B>(f: (a: A) => B): Opt<B> {
return new Some(f(this.a))
}
flatMap<B>(f: (a: A) => Opt<B> | MaybeNull<B>): Opt<B> {
const b = f(this.a)
return isOpt(b) ? b : Opt(b)
}
filter(f: (a: A) => boolean): Opt<A> {
return Opt(f(this.a) ? this.a : undefined)
}
forEach(f: (a: A) => void): this {
f(this.a)
return this
}
getOrElse(_orElse: () => A): A {
return this.a
}
orElse(_orElse: () => Opt<A>): Opt<A> {
return this
}
zip1<B, T>(b: MaybeOpt<B>, f: (a: A, b: B) => MaybeOpt<T>): Opt<T> {
return Opt(b).flatMap(eb => f(this.a, eb))
}
zip2<B, C, T>(
b: Opt<B>,
c: Opt<C>,
f: (a: A, b: B, c: C) => MaybeOpt<T>
): Opt<T> {
return Opt(b).flatMap(eb => Opt(c).flatMap(ec => f(this.a, eb, ec)))
}
zip3<B, C, D, T>(
b: MaybeOpt<B>,
c: MaybeOpt<C>,
d: MaybeOpt<D>,
f: (a: A, b: B, c: C, d: D) => MaybeOpt<T>
): Opt<T> {
return Opt(b).flatMap(eb =>
Opt(c).flatMap(ec => Opt(d).flatMap(ed => f(this.a, eb, ec, ed)))
)
}
}
/**
* @see http://www.scala-lang.org/api/current/scala/Option.html
*/
export function Opt<A>(a: MaybeOpt<A>): Opt<A> {
return isOpt(a) ? a : a != null ? new Some(a) : None
}
export function isOpt<A>(a: MaybeOpt<A>): a is Opt<A> {
return a instanceof Some || a === None
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment