-
-
Save Rafe/6943665 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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