Loading ...
Sorry, an error occurred while loading the content.

727Re: [jslint] Nested ?: operator values.

Expand Messages
  • pauanyu
    Jul 9, 2009
    • 0 Attachment
      --- In jslint_com@yahoogroups.com, Michael Lorton <mlorton@...> wrote:
      >
      > Well, val1 and val2 are the only possible values, you could do this:
      >
      > var next = {};
      > next[val1]=val2;
      > next[val2]=val1;
      > return this[prop] = next[this[prop]] ;
      >
      > If the function is to be executed over and over, the first three statement are only needed at initialization time. Plus, this algorithm generalizes to any fixed, repeating sequence of values. Say you wanted to loop through 1, 4, 9 over and over (starting at 1 if the property is not already in the sequence):
      >
      > return this[prop] = { 1: 4, 4: 9, 9: 1} [this[prop]] || 1;
      >
      > Was this the question or did you want to talk about the ternary operator?
      >
      > M.
      >

      I did a little tinkering, and here's what I came up with:

      return (this[prop] = ({ val1: val2, val2: val1 })[this[prop]]);

      What a fantastic construct. Create an anonymous object, then use it immediately! Unfortunately this doesn't work, because val1 and val2 are variables that are determined at run-time, so this will fail.

      Nonetheless, you have my gratitude for pointing out a wonderful construct that I plan to use more often in my code. For now, I'll stick with the ?: operator.
    • Show all 7 messages in this topic