Skip to content

Instantly share code, notes, and snippets.

@Gab-km
Created March 2, 2012 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gab-km/1958526 to your computer and use it in GitHub Desktop.
Save Gab-km/1958526 to your computer and use it in GitHub Desktop.
Option, which you may know as 'Maybe'.
function write(message) {
document.getElementById("output").innerHTML += message + "<br />";
}
function assertEquals(expected, actual) {
if (expected === actual) {
write("OK");
} else {
var text = "expected = [" + expected.toString()
+ "], but actual = [" + actual.toString() + "]."
write("Failure: " + text);
}
}
function assertTrue(target) {assertEquals(true, target);}
function assertFalse(target) {assertEquals(false, target);}
document.write('<script type="text/javascript" src="myJsUnit.js"></script>');
function Option(){};
Option.prototype = {
isSome : function(){},
bind : function(f) {}
};
function Some(value) {
Option.call(this);
this.value = value;
}
Some.prototype = new Option();
Some.prototype.isSome = function() { return true; };
Some.prototype.bind = function(f) { return f(this.value); };
function None() {
Option.call(this);
}
None.prototype = new Option();
None.prototype.isSome = function() { return false; };
None.prototype.bind = function(f) { return this; };
function option(x) {
if (x < 0) {
return new None();
} else {
return new Some(x);
}
}
function tryAdd(x, y) {
return option(x).bind(function(a){
return option(y).bind(function(b){
return option(a+b)
})
});
}
function testSuite() {
var some3 = tryAdd(1, 2);
assertTrue(some3.isSome());
assertEquals(3, some3.value);
var none = tryAdd(4, -1);
assertFalse(none.isSome());}
window.onload = testSuite;
<!DOCTYPE html>
<html>
<head>
<title>Option test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="option.js"></script>
</head>
<body>
<div id="output" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment