Skip to content

Instantly share code, notes, and snippets.

View choonkending's full-sized avatar

Ken Ding choonkending

  • REA Group
  • Australia
View GitHub Profile
const transformCage = () => { /* ... */ };
const handleError = e => "Invalid or Corrupted User Data";
const handleSuccess = data => "Success";
const doSomethingWithUserData = () =>
getUserFromLocalStorage('nickCage')
.map(transformCage)
.fold(handleError, handleSuccess);
const getUserFromLocalStorage = keyName => {
const str = localStorage.getItem(keyName);
try {
return Right(JSON.parse(str));
} catch (e) {
return Left("Invalid or Corrupted User Data");
}
};
const getUserFromLocalStorage = keyName => {
const str = localStorage.getItem(keyName);
try {
return JSON.parse(str);
} catch (e) {
return "Invalid or Corrupted User Data";
}
};
const doSomethingWithUserData = () => {
const cage = getUserFromLocalStorage('cage');
// do wonderful things
};
const getUserFromLocalStorage = keyName => {
const str = localStorage.getItem(keyName);
return JSON.parse(str);
};
const Left = x => ({
map: f => Left(x),
fold: (ifLeft, ifRight) => ifLeft(x)
});
const Right = x => ({
map: f => Right(f(x)),
fold: (ifLeft, ifRight) => ifRight(x)
});
const getBedrooms = data =>
Option(data.listing)
.flatMap(listing => Option(listing.features))
.flatMap(features => Option(features.bedrooms))
.map(bedrooms => bedrooms.value)
.fold(() => 0, v => v);
const Option = x => (x === undefined || x === null) ? None : Some(x);
const Some = x => ({
map: f => Some(f(x)),
flatMap: f => f(x),
fold: (ifEmpty, f) => f(x)
});
const None = {
map: f => None,
const ComponentThatWrapsFeatures = ({ data }) => {
const features = getFeatures(data);
return features && <Features {...features} />
};
const Features = ({ bedrooms, bathrooms }) => (
<div>
<span>Beds: </span><span>{ bedrooms }</span>
<span>Baths: </span><span>{ bathrooms }</span>
</div>
);