Apologies for the malformed title, I can't really think of a better way to describe what I mean to say. Here is my current code:
fromEn = true; // some boolean value
options = {
from: fromEn ? "en" : "es",
to: fromEn ? "es" : "en"
};
I want from to be "en" when fromEn is true and "es" when it's false. to should be the "opposite value" of from, so-to-speak. I feel my current code is too redundant, and although it works I'd like a more elegant solution. Is there a better way of achieving what I'm trying to do?
EDIT: I decided that ternaries are the best way to go. See Emissary's solution for what I've chosen to do, and see my answer lower to find three possible solutions. Thank you all for the help!
const args = ["es", "en"]; options = { from: args[0^fromEn], to: args[1^fromEn]}but if this is any better? I'd doubt it. I'd bet that even you would wonder what this is/does in like 2 months from now.^is not a logical operator. instead it's a bitwise XOR^operator.options = fromEn ? {from:'en',to:'es'} : {from:'es',to:'en'}more idiomatic though it's really down to personal preference.const [from, to] = fromEn? ["en", "es"]: ["es", "en"]; options = { from, to };or @101arrows if you're still on the lookout for dirty hacks that you won't understand anymore when taking a look at, the next time:const [from, to] = ["en", "es", "en"].slice(+fromEn); options = { from, to };. I like to play around with that kind of hacks, but these should never turn up in production code.