Skip to content

Instantly share code, notes, and snippets.

@pspeter3
Last active March 4, 2016 18:18
Show Gist options
  • Save pspeter3/a3c4bed9b39a8be33859 to your computer and use it in GitHub Desktop.
Save pspeter3/a3c4bed9b39a8be33859 to your computer and use it in GitHub Desktop.
Lambda: A simple functional TypeScript library

Lambda

This is just meant to be a small proof of concept functional programming libray for TypeScript which handles working with Releasables, Maps, Maybes, and Results.

export interface Releasable {
release();
}
export interface Handle<T> extends Releasable {
value(): T;
}
export interface Map<T> {
[key: string]: T;
}
export interface Set extends Map<boolean> {}
export type Maybe<T> = T | void;
export type Either<T, U> = T | U;
export type Result<T> = Either<Error, T>;
export namespace maybe {
export function isNone<T>(adt: Maybe<T>): adt is void {
return adt === undefined || adt === null;
}
export function isValue<T>(adt: Maybe<T>): adt is T {
return !isNone(adt);
}
export function map<T, U>(adt: Maybe<T>, callback: (value: T) => U): Maybe<U> {
if (isNone(adt)) {
return adt;
} else {
return callback(adt);
}
}
}
export namespace result {
export function isError<T>(adt: Result<T>): adt is Error {
return adt instanceof Error;
}
export function isValue<T>(adt: Result<T>): adt is T {
return !isError(adt);
}
export function map<T, U>(adt: Result<T>, callback: (value: T) => U): Result<U> {
if (isError(adt)) {
return adt;
} else {
return callback(adt);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment