Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Generators let you cut away at boiler-plate. Here I'm using it to do similar things to Haskell's Maybe, which effectively defines an error state (e.g NaN) once, and then write a lot of code that doesn't now have to bother checking for it explicitly. The numericalProcess can now be defined without any checking for NaN, in a point-free (not refere…
var Nothing = {Nothing: true}
function MaybeGenerator() {
var g = arguments[arguments.length - 1]
// list of functions that test for any "Nothing" values
var maybes = [],0,arguments.length - 1)
return function(value) {
var generator = g.apply(null,[],1))
var result
var nothing = false
while(result =, !result.done) {
value =,value)
if(maybes.some(function(mf) { return mf(value) })) {
return Nothing
return value
var numericalProcess = function*() {
yield Math.log
yield function(x) { return x - 1 }
yield Math.log
yield Math.sqrt
yield Math.log
var safeNumericalExample = MaybeGenerator(isNaN,numericalProcess)
var shouldBeNothing = safeNumericalExample(-1)
var becomesNothingLater = safeNumericalExample(1)
var someNormalNumber = safeNumericalExample(1205)
console.log(shouldBeNothing) // Nothing
console.log(becomesNothingLater) // Nothing
console.log(someNormalNumber) // 0.29592896553598536...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.