Last active
August 29, 2015 14:17
-
-
Save JakeSidSmith/c143a9a9bf774084077b to your computer and use it in GitHub Desktop.
Messing around with promise-like syntax for if statements
This file contains 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 ifTrue = function (value) { | |
var resolved, stored; | |
var result = value; | |
return { | |
then: function (fn) { | |
if (value) { | |
if (typeof fn === 'function') { | |
fn(); | |
} else { | |
stored = fn; | |
resolved = true; | |
} | |
} | |
return this; | |
}, | |
elseIf: function (elseValue) { | |
if (elseValue && !resolved) { | |
value = !value && elseValue; | |
resolved = true; | |
} | |
return this; | |
}, | |
else: function (fn) { | |
if (!value && !resolved) { | |
if (typeof fn === 'function') { | |
fn(); | |
} else { | |
stored = fn; | |
} | |
} | |
return this; | |
}, | |
return: function () { | |
return stored; | |
} | |
}; | |
}; | |
ifTrue(false) | |
.then(function () { | |
console.log('if'); | |
}) | |
.elseIf(true) | |
.then(function () { | |
console.log('else if'); | |
}) | |
.else(function () { | |
console.log('else'); | |
}); | |
var message = ifTrue(false).then('Hello').else('World').return(); | |
console.log(message); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment