Skip to content

Instantly share code, notes, and snippets.

@Rafe
Forked from timruffles/maybe-es6.js
Created October 11, 2013 23:37
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 Rafe/6943665 to your computer and use it in GitHub Desktop.
Save Rafe/6943665 to your computer and use it in GitHub Desktop.
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