Generate next sequence of an "index"

2

I have a problem generating a string for an "index".

As an example, if I get the number 1.2, I wanted to generate the number 1.2.4 as a string or if I get 1.2.2 I wanted to generate 1.2.2.1

<select>
  <option>1.1       </option>
  <option>1.1.1     </option>
  <option>1.1.2     </option>
  <option>1.2       </option>
  <option>1.2.1     </option>
  <option>1.2.2     </option>
  <option>1.2.3     </option>
  <option>1.2.3.1   </option>
  <option>1.3       </option>
  <option>1.3.1     </option>
</select>

In case I would have to check how many elements this "index" would have and generate a new one, but I'm having a problem with its logic.

If anyone can help. Thanks in advance.

    
asked by anonymous 15.05.2018 / 19:22

1 answer

2

You can do this. The explanations are commented on in the code:

$("select").change(function(){
   
   var opts = $("option", this); // pego todos os options
   var opt  = $(":selected", this); // pego o option selecionado
   var idx  = opt.index(); // pego o índice do option selecionado
   var txt  = opt.text().trim(); // pego o texto do option e elimino os espaços nas bordas
   var m; // flag para testar regex

   // aqui verifico se existe uma subsequência com .1
   for(var x=idx+1; x<opts.length; x++){
      var re = new RegExp("^"+txt+".1");
      m = re.test($(opts[x]).text().trim());
      if(m) break;
   }

   if(m){ // se existe, varro o resto do select para definir a próxima sequência
      var y = 2; // começo com 2, já que o 1 já existe
      for(var x=idx+2; x<opts.length; x++){
         var txt2 = $(opts[x]).text().trim();
         var re = new RegExp("^"+txt+"."+y);
         m = re.test(txt2);
         if(!m) break;
         y++;
      }
      var seq = txt+"."+y;
   }else{ // se não existe, crio a subsequência com .1
      var seq = txt+".1";
   }
   
   console.log(seq);
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option>1.1       </option>
  <option>1.1.1     </option>
  <option>1.1.2     </option>
  <option>1.2       </option>
  <option>1.2.1     </option>
  <option>1.2.2     </option>
  <option>1.2.3     </option>
  <option>1.2.3.1   </option>
  <option>1.3       </option>
  <option>1.3.1     </option>
  <option>1.3.2     </option>
  <option>1.3.3     </option>
  <option>1.3.4     </option>
  <option>1.3.5     </option>
  <option>1.3.6     </option>
  <option>1.3.7     </option>
  <option>3         </option>
</select>
    
15.05.2018 / 20:39