Skip to content

Instantly share code, notes, and snippets.

View choonkending's full-sized avatar

Ken Ding choonkending

  • REA Group
  • Australia
View GitHub Profile
// https://medium.com/@gcanti/higher-kinded-types-in-typescript-static-and-fantasy-land-d41c361d0dbe
import {
TypeConstructors,
TypeConstructors2,
Kind,
Kind2,
} from "./higherKindedTypes";
export interface Functor<F extends TypeConstructors, A> {

Use Case

/* @flow */
type Props = { foo: string };
const View = ({ foo }: Props) => <div>{ foo }</div>;

// Consumer renders View
Some(x) None
map map<V>(f: (value: U) => V): Some<V>
map flatMap fold
Some(x)
const getBedrooms = data => {
const bedrooms = data.listing && data.listing.features && data.listing.features.bedrooms;
if (bedrooms) {
return bedrooms.value;
}
return 0;
};
const getUserFromLocalStorage = keyName => {
const str = localStorage.getItem(keyName);
try {
return Right(Option(JSON.parse(str)));
} catch (e) {
return Left("Invalid or Corrupted User Data");
}
};
/* Option types */
const Option = x => (x === undefined || x === null) ? None : Some(x);
const Some = x => ({
filter: f => f(x) ? Some(x) : None,
map: f => Some(f(x)),
fold: (ifEmpty, f) => f(x),
getOrElse: defaultValue => x
});
const getFeatures = data => {
if (data && data.listing && data.listing.features) {
const { bedrooms, bathrooms } = data.listing.features;
const beds = bedrooms && bedrooms.value || 0;
const baths = bathrooms && bathrooms.value || 0;
if (beds === 0 && baths === 0) return null;
return {
bedrooms: beds,
bathrooms: baths
};
const transformCage = () => { /* ... */ };
const handleError = e => "failed to parse Cage";
const handleSuccess = data => "Success";
const ifEmpty = () => "Cage does not exist!";
const doSomethingWithUserData = () =>
getUserFromLocalStorage('nickCage')
.fold(handleError,
data =>
data.map(transformCage)