Created
March 2, 2012 13:54
-
-
Save Gab-km/1958526 to your computer and use it in GitHub Desktop.
Option, which you may know as 'Maybe'.
This file contains 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
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);} |
This file contains 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
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; |
This file contains 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
<!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