Skip to content

Instantly share code, notes, and snippets.

@edew
Created November 13, 2019 11:26
Show Gist options
  • Save edew/e00e5efc322d4c9e671732d2d5be289f to your computer and use it in GitHub Desktop.
Save edew/e00e5efc322d4c9e671732d2d5be289f to your computer and use it in GitHub Desktop.
TypeScript Option 1
abstract class Option<T> {
abstract map<U>(f: (value: T) => U): Option<U>;
abstract defaultValue(defaultValue: T): T;
}
class Some<T> extends Option<T> {
private value: T;
constructor(value: T) {
super();
this.value = value;
}
map<U>(f: (value: T) => U): Option<U> {
return new Some(f(this.value));
}
defaultValue(_defaultValue: T): T {
return this.value;
}
}
class None<T> extends Option<T> {
constructor() {
super();
}
map<U>(_f: (value: T) => U): Option<U> {
return new None();
}
defaultValue(defaultValue: T): T {
return defaultValue;
}
}
const maybeParseInt = (s: string): Option<number> => {
const result = parseInt(s);
if (isNaN(result)) {
return new None();
} else {
return new Some(result);
}
};
maybeParseInt("foo").map(n => n + 5).defaultValue(0) // 0
maybeParseInt("10").map(n => n + 5).defaultValue(0) // 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment