Skip to content

Instantly share code, notes, and snippets.

@kimamula
Last active December 3, 2020 20:12
Show Gist options
  • Save kimamula/e9719145ec7598a43a66 to your computer and use it in GitHub Desktop.
Save kimamula/e9719145ec7598a43a66 to your computer and use it in GitHub Desktop.
Implementation of Optional (Maybe) in TypeScript
class Some<A> implements Optional<A> {
constructor(private a: A) {
}
getOrElse(a: A) {
return this.a;
}
map<B>(func: (a: A) => B) {
return Optional(func(this.a));
}
match<B>(cases: {
some: (a: A) => B;
none: () => B;
}): B {
return cases.some(this.a);
}
}
const None: Optional<any> = {
getOrElse(a: any) {
return a;
},
map() {
return this;
},
match<B>(cases: {
some: (a: any) => B;
none: () => B;
}): B {
return cases.none();
}
}
interface Optional<A> {
match<B>(cases: {
some: (a: A) => B;
none: () => B;
}): B;
getOrElse(a: A): A;
map<B>(func: (a: A) => B): Optional<B>;
}
function Optional<A>(a: A): Optional<A> {
if (typeof a === 'undefined' || a === null) {
return None;
} else {
return new Some(a);
}
}
export default Optional;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment