Skip to content

Instantly share code, notes, and snippets.

@timruffles
Last active December 20, 2015 12:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save timruffles/6129848 to your computer and use it in GitHub Desktop.
Save timruffles/6129848 to your computer and use it in GitHub Desktop.
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 = [].slice.call(arguments,0,arguments.length - 1)
return function(value) {
var generator = g.apply(null,[].slice.call(arguments,1))
var result
var nothing = false
while(result = generator.next(), !result.done) {
value = result.value.call(null,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