Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript jQuery Plugin Conditional Logic Reply To: jQuery Plugin Conditional Logic

#169721
dyr
Participant

Two more questions to throw out there.

When I’m checking certain parameters I’m using ternary operators since there are only two options, for example:

getLimitMode: function() {
      // set mode based on data-attr's
      var mode = !!this.element$.attr( 'data-limit-char'  )
        ? "character"
        : !!this.element$.attr( 'data-limit-word' )
          ? "word"
          : "";

    // set max based on mode
    this.limitMax = mode == "character"
      ? this.element$.attr( 'data-limit-char' )
      : this.element$.attr( 'data-limit-word' );

    // crude check of improper data attr
      if ( mode == "" ) {
        console.log( "Please set a data-limit-word or data-limit-char attribute!" );
      }
      return mode;
}

You can see there’s a super crude check to see if the data-attribute is not set, however that’s the only validation of configuration I’m doing at this point. I’m wondering what a better approach to this would be. I’ve seen some suggestions that I could check if the value is invalid first and throw an exception then check the values individually and assign the correct string.

And secondly, I’m wondering how I might optimize this function which has some compound conditionals (is that a real term?):

validateCount: function( count ) {
      if (
        // direction is up and count exceeds max OR
        // direction is down and count is less than 0
        ( this.settings.limitDirection == "up"   && count > this.limitMax ) ||
        ( this.settings.limitDirection == "down" && count < 0 ) ) {

        // invalidate
        this.limitElement$
          .removeClass( this.settings.limitValidClass )
          .addClass( this.settings.limitInvalidClass );

      } else if (
        // direction is up and count is greater than 0 and less than or equal to max OR
        // direction is down and count is greate than or equal to 0 and not equal to max
        ( this.settings.limitDirection == "up"   && count > 0  && count <= this.limitMax ) || 
        ( this.settings.limitDirection == "down" && count >= 0 && count != this.limitMax ) ) {

        // validate
        this.limitElement$
          .removeClass( this.settings.limitInvalidClass )
          .addClass( this.settings.limitValidClass );           
      }
    }

Cheers