JavaScript for WordPress Forums Vanilla JavaScript 1.3.11 – updateIdStr() function

This topic contains 1 reply, has 2 voices, and was last updated by  Zac Gordon 3 years, 5 months ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #7623

    Thorsten Frommen
    Participant

    Of course, I don’t know if you wanted to use only stuff that you already covered before, or present (i.e., teach to) code that is on the one hand not so hard to understand but on the other not the very naive approach as well.

    I would suggest an optimized (as well as condensed) function.

    Here’s the original one:

    function updateIdStr( value ) {
    
      var strArray = value.split( '-' ),
          id = strArray[ strArray.length - 1 ],
          newId = parseInt( id ) + 1;
    
      strArray[ strArray.length - 1 ] = newId;
      return strArray.toString().replace( ',' , '-' );
    
    }

    And here’s the optimized one:

    function updateIdStr( value ) {
    
      var strArray = value.split( '-' );
    
      strArray[ strArray.length - 1 ]++;
      return strArray.join( '-' );
    
    }
    

    Less variables, less (unnecessary) calculcations, but one on-the-fly incrementing.
    New is the usage of Array.prototype.join().

    #7628

    Zac Gordon
    Keymaster

    Thanks Thorsten!

    Yes, as you point out, was just showing a process with more steps including things had covered, but will throw this up as an example as well 🙂

    Once we get into building the project we will take an approach like the one you have suggested 🙂

    Thanks!

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.