Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I need to set unit's exhaust.

A unit might have a turnScript, and the turnScript might have a delay. If so, unit.exhaust = unit.turnScript.delay. Otherwise, unit.exhaust = -1.

This is what I have now. It works, but it's repetitive and unidiomatic.

unit.exhaust = unit.turnScript && unit.turnScript.delay ? unit.turnScript.delay : -1;

I tried these two as well:

unit.exhaust = unit.turnScript ? unit.turnScript.delay : -1 || -1;

and

unit.exhaust = {unit.turnScript ? unit.turnScript.delay : -1} || -1;

But the first returns undefined when turnScript exists but not delay, and the second gives me a syntax error (unexpected .). Is there a better way to do it?

share|improve this question
    
:( I was hoping there would be a more succinct way to say it, it's really long. –  Devon Parsons Jun 7 at 20:59
    
Not a ternary, but you could make a function that you'd pass the base object and the two property names to and the function would return the desired result. –  jfriend00 Jun 7 at 21:00
    
Nah, it wouldn't make sense. Pretty much all the units stats are calculated differently, it wouldn't get reused. Thanks though. –  Devon Parsons Jun 7 at 21:00
    
(Note: @jfriend00's comment is now slightly out-of-date. The 'second one' when he commented is the third one as of this comment -- unit.exhaust = {unit.turnScript ? unit.turnScript.delay : -1} || -1;) –  QPaysTaxes Jun 7 at 22:57

1 Answer 1

up vote 3 down vote accepted

You can use short-circuit logic for the whole thing (a ternary is unnecessary). Consider the tree cases:

unit = {}
unit = {turnScript: {}}
unit = {turnScript: {delay: 5}

the results for the output should be:

-1
-1
5

Simple fall-through logic operators will do it:

unit.exhaust = unit.turnScript && unit.turnScript.delay || -1;

as a snippet, this is:

function truthtable(unit) {
  return unit.turnScript && unit.turnScript.delay || -1;
}

var dataNTS = {},
    dataTS = {turnScript: {}},
    dataDel = {turnScript: {delay: 5}};

var out = document.getElementById("output");

out.innerHTML += truthtable(dataNTS) + "\n";
out.innerHTML += truthtable(dataTS) + "\n";
out.innerHTML += truthtable(dataDel) + "\n";
<pre id="output"></pre>

The above function consists of:

  unit.turnScript && unit.turnScript.delay || -1;

It covers the basic use cases and falls through when it has a good answer. The three cases are given as example inputs.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.