tags:

views:

62

answers:

5

Is there a shorter way to write this?

var ttt = "dd";
if (ttt.length < 3) 
ttt= "i" + ttt;
+3  A: 

Yours is pretty short, but if you want to use the the conditional operator (a.k.a the ternary operator), you could do the following:

var ttt = "dd";
ttt = ttt.length < 3 ? "i" + ttt : ttt;

... or if bytes are really precious (code golfing?), you could also do something like this:

var ttt = "dd".length < 3 ? "i" + "dd" : "dd";

... but then that could be reduced to just:

var ttt = "idd";

... as @Nick Craver suggested in a comment below.

Daniel Vassallo
+1 - I dunno though....`var ttt = "idd";` seems *pretty* short ;) Also, you need quotes around the `i` to be 100% on this one ;)
Nick Craver
@Nick Fixed: Thought it was a variable at first.
Daniel Vassallo
@Daniel - A+++++++ would do business again
Nick Craver
@Nick: lol! :) -
Daniel Vassallo
A: 

Or :

var ttt = "dd";
ttt = (ttt.length < 3 ? i : "") + ttt;
Antares
+2  A: 

The shortest with the same result is:

var ttt="idd";

because "dd" has a length of 2. so the if is always true and you'll always prepend "i"

davyM
+1  A: 

Another option is to use a regex:

var ttt = "dd".replace(/^(\w?\w?)$/, 'i$1');

But then you have 2 problems :)

Mic
A: 

Also there's a way with && operator instead of if

var ttt = "dd";
ttt.length < 3 && (ttt = "i" + ttt);
fantactuka