Skip to content

Instantly share code, notes, and snippets.

@snichme
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save snichme/9536129 to your computer and use it in GitHub Desktop.

Select an option

Save snichme/9536129 to your computer and use it in GitHub Desktop.
Maybe.js
class Maybe {
constructor(val) {
this.val = val;
}
map(f) {
return this.val ? new Maybe(f(this.val)) : new Maybe();
}
toString() {
return 'Maybe('+this.val+')';
}
}
// Syntactic suga
var map = (f, obj) => obj.map(f);
/* Named mapping functions to test with */
var log = (val) => console.log("%s", val);
var toLower = (val) => val.toLowerCase();
var first = (xs) => {
if(!xs) return null;
else return xs[0];
};
var debug = (fn) => {
return (val) => {
var fnName = fn.name || 'fn';
var res = fn(val);
console.log('debug: ' + fnName + '('+val+') = ' + res);
return res;
}
};
var prop = (key) => {
return (obj) => {
if(obj[key]) {
return obj[key];
}
return null;
};
}
var username = prop('username');
var isAuthed = true;
function getUser() {
if(isAuthed) {
return new Maybe({username: "snichme", email: "mange@mange.name"});
} else {
return new Maybe();
}
}
console.log();
console.log("isAuthed = " + isAuthed);
map(log, map(username, getUser()));
map(log, map(prop('email'), getUser()));
isAuthed = false;
console.log("isAuthed = " + isAuthed);
map(log, map(username, getUser()));
console.log();
console.log();
// Example
map(log, map(debug(toLower), new Maybe("Firstname Lastname")));
map(log, map(toLower, new Maybe()));
map(log, map(debug(first), new Maybe("Firstname Lastname")));
map(log, map(first, new Maybe()));
map(log, map(first, new Maybe(['A', 'B', 'C'])));
map(log, map(debug(toLower), new Maybe("Username Username")));
map(log, map(first, map(toLower, new Maybe("Username Username"))));
var me = new Maybe("Magnus Andersson");
me.map(debug(toLower)).map(log);
['A', 'B'].map(debug(toLower)).map(log);
map(log, map(debug(toLower), ['A', 'B', 'C']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment