An educational pure functional programming library in TypeScript
2
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add prelude/option module with Option type and operations

+39
+1
src/prelude/index.ts
··· 1 1 export * from "./compose" 2 2 export * from "./result" 3 + export * from "./option"
+38
src/prelude/option.ts
··· 1 + // Types 2 + export type Some<T> = { readonly _tag: "Some"; readonly value: T } 3 + export type None = { readonly _tag: "None" } 4 + export type Option<T> = Some<T> | None 5 + 6 + // Constructors 7 + export const some = <T>(value: T): Some<T> => ({ _tag: "Some", value }) 8 + export const none: None = { _tag: "None" } 9 + 10 + // Type guards 11 + export const isSome = <T>(o: Option<T>): o is Some<T> => o._tag === "Some" 12 + export const isNone = <T>(o: Option<T>): o is None => o._tag === "None" 13 + 14 + // From nullable 15 + export const fromNullable = <T>(value: T | null | undefined): Option<T> => 16 + value == null ? none : some(value) 17 + 18 + // Operations - expression only 19 + export const mapOption = <T, U>(f: (t: T) => U) => 20 + (option: Option<T>): Option<U> => 21 + option._tag === "Some" ? some(f(option.value)) : none 22 + 23 + export const flatMapOption = <T, U>(f: (t: T) => Option<U>) => 24 + (option: Option<T>): Option<U> => 25 + option._tag === "Some" ? f(option.value) : none 26 + 27 + export const getOrElse = <T>(defaultValue: T) => 28 + (option: Option<T>): T => 29 + option._tag === "Some" ? option.value : defaultValue 30 + 31 + export const matchOption = <T, R>( 32 + onSome: (value: T) => R, 33 + onNone: () => R 34 + ) => (option: Option<T>): R => 35 + option._tag === "Some" ? onSome(option.value) : onNone() 36 + 37 + export const toNullable = <T>(option: Option<T>): T | null => 38 + option._tag === "Some" ? option.value : null