Last active
December 3, 2020 20:12
-
-
Save kimamula/e9719145ec7598a43a66 to your computer and use it in GitHub Desktop.
Implementation of Optional (Maybe) in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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