Created
March 7, 2012 15:10
-
-
Save bga/1993712 to your computer and use it in GitHub Desktop.
[fun] various forms of ternary operator in JavaScript
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
// add your variants of | |
a ? b : c | |
// in comments :) | |
// a is boolean | |
// b and c - any type | |
// lazy evaluation isnt important |
Shouldn't this:
[c, b][a]
Be this: (?)
[c, b][+!!a]
Or:
[b,c][+!a]
IMHO, this is the most readable ternary operation:
Array(2).concat(b, c)[String(a).match(/(t)|(f)/).join().split(',,').push(1)]
@padolsey It could simply be [c, b][+a]
, as the gist states that a
is a boolean (not just a truthy/falsy value). But yeah, [c, b][a]
doesn’t look right.
I believe
[c, b][a]
should be
[c, b][+a]
Edit: Damn you mathias! :)
@jneira I love that lambda calculus inspired version. How about this? (Credits to you, this is just sugar)
var lambdas = {
true: function(x) {return function(y) {return x}},
false: function(x) {return function(y) {return y}},
ifthenelse: function (x) { return function(y) { return function(z) {return (x(y))(z)}}}
}
function ternary (a,b,c) {
return lambdas.ifthenelse(lambdas[!!a])(function(_) {return b})(function(_){return c})()
}
console.log(ternary("a","b","c"))
// b
console.log(ternary(false,"b","c"))
//c
better, but credits to Alonzo Church!, we are simple mortals
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[c, b][a] doesn't work for me: it returns undefined, which seems expected. But [c, b][ ~ ~ a] works for true/false/1/0 and [c, b][!! ~ ~ a] works for negative numbers (at least if you expect them to resolve to true).