Skip to content

Instantly share code, notes, and snippets.

@b-studios
Last active December 26, 2015 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b-studios/7169568 to your computer and use it in GitHub Desktop.
Save b-studios/7169568 to your computer and use it in GitHub Desktop.
Encoding Haskells `Maybe` or Scala's `Option` type in JavaScript using the new generators (es6)
function Option(value) {
this.value = value;
this.some = arguments.length == 1
}
Option.none = new Option()
Option.some = v => new Option(v)
Option.prototype.iterator = function () {
if (this.some) yield this.value
}
var opts = [Option.some(3), Option.none, Option.some(4)]
for (let el of opts)
for (let v of el)
console.log(v)
// yields:
// 3
// 4
// using the spread operator to unpack the option
console.log( [1, 2, ...Option.some(3), ...Option.none, 4] )
// yields: [1, 2, 3, 4]
// Example: working with computations, that might fail
function rand() {
return Math.random() * 20
}
function f1(x) {
if (x > 10)
return Option.some(x)
else
return Option.none
}
function f2(x, y) {
if (y == 0)
return Option.none
else
return Option.some(x / y);
}
for (let x of f1(rand()))
for (let y of f1(rand()))
for (let res of f2(x, y))
console.log( res )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment