More Actionscript One-Liners

March 27th, 2007

I’ve been having some fun working out new speedy lines of code using operators

// if str is blank, pass an alternative string
return str || "str is blank";

// if obj isn't active, return null
return (obj.isActive && obj) || null;

// If num is zero, return "1" instead
return num || 1;

// If num is zero or not a real number (including NaN), return "1" instead
return (isFinite(num) && num) || 1;

// If num is less than 0 or not a real number, return "0" instead
return (isFinite(num) && num > 0 && num) || 0;

// add an entry to a list that is created if it doesn't exist
(arr || (arr = [])).push(entry);

Anybody have other ideas?

4 Responses to “More Actionscript One-Liners”

  1. Keith Peters Says:

    Personally, I don’t like that kind of syntax. Not as clear as an if statement, and you are counting on various data type conversions to Boolean, which I’d rather be more explicit about. For real simple statements I occasionally might do that kind of thing, but in most cases, I’d create an if statement. Lines of code are free. 🙂

  2. Max Says:

    Keith: True, but most of these lines are faster than their counterparts. There’s no boolean conversions either, the operators don’t work that way in AS3 (at least not anymore). I agree that these aren’t as readable, but when you need fast code readability goes out the window.

    Haven’t you ever had to make sure a number is finite, not NaN and above zero before? It’s a lot nicer to do it in one line.

  3. spender Says:

    to quick floor a floating point number:

    x=x>>0;

  4. jacob Says:

    I wouldn’t mind working with this code as long as it was commented as it is above. this stuff is more difficult to troubleshoot if its not working correctly though.

    this is a good read on optimization

    http://flasm.sourceforge.net/

Leave a Reply