Skip to content

Instantly share code, notes, and snippets.

@frne
Created February 8, 2024 08:59
Show Gist options
  • Save frne/8e81d8052f32f0d9363797e1894339bf to your computer and use it in GitHub Desktop.
Save frne/8e81d8052f32f0d9363797e1894339bf to your computer and use it in GitHub Desktop.
Function TS Option type
export abstract class Option<T> {
protected value: T | null;
static of<T>(value: T | null): Option<T> {
if (value == null) {
return new None();
} else {
return new Some(value);
}
}
protected constructor(value: T | null) {
this.value = value;
}
public isSome(): boolean {
return this.value != null;
}
public isNone(): boolean {
return !this.isSome();
}
public fold<A>(someFn: (t: T) => A, noneFn: () => A): A {
if (this.value != null) {
return someFn(this.value);
} else {
return noneFn();
}
}
public map<A>(fn: (t: T) => A): Option<A> {
return this.flatMap((x) => some(fn(x)));
}
public flatMap<A>(fn: (t: T) => Option<A>): Option<A> {
return this.fold(
(x) => fn(x),
() => none()
);
}
public filter(fn: (t: T) => boolean): Option<T> {
if (this.value != null && fn(this.value)) {
return some(this.value);
} else {
return none();
}
}
public orElse(t: T): T {
return this.fold(identity, () => t);
}
}
export class Some<T> extends Option<T> {
constructor(value: T) {
super(value);
}
}
export class None<T> extends Option<T> {
constructor() {
super(null);
}
}
export function some<T>(value: T): Some<T> {
return new Some(value);
}
export function none<T>(): None<T> {
return new None();
}
const identity = <B>(x: B) => x;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment