How to reduce the amount of If’s in a simultaneous redirect?

Asked

Viewed 74 times

1

I have a function called redirectToNextPage that does the following: Takes the value of the URL from the previous page and, after three seconds, redirects to the next page, using an IF for each URL, with one exception, because the home page can start without the final parameter that I configured through queryParams.

I’m taking the URL of the inner page inside the class builder:

this.history = document.referrer
/// O document.referrer existe porque ele está redirecionando para essa página através de um link.

That is the function :

redirectToNextPage() {
        if (this.history === 'http://127.0.0.1:5500/quiz.html' || this.history === 'https://127.0.0.1:5500/quiz.html?quiz=1') {
            setTimeout(() => {
                window.location.href = 'http://127.0.0.1:5500/quiz.html?quiz=2'
            }, 3000);
        }
        if (this.history === 'http://127.0.0.1:5500/quiz.html?quiz=2') {
            setTimeout(() => {
                window.location.href = 'http://127.0.0.1:5500/quiz.html?quiz=3'
            }, 3000);
        }
        if (this.history === 'http://127.0.0.1:5500/quiz.html?quiz=3') {
            setTimeout(() => {
                window.location.href = 'http://127.0.0.1:5500/quiz.html?quiz=4'
            }, 3000);
        }

Well, the function goes like this until the 'quiz.html.? quiz=10'. However, I decided not to put the whole function here so as not to become giant so you don’t get bored.

In short. What I want is to change the end of the URL, adding an extra number at its end, each time it is redirected to the specific page.

What I tried to:


let historyArray = this.history.split('')
let takeLastNumber = historyArray.pop()
console.log(historyArray)
console.log(historyArray.join())

for (var i = 1; i <= 10; i++) {
            console.log('http://127.0.0.1:5500/quiz.html?quiz=' + i)   
        }

I tried to transform the string into an array, take out the last element of it - which is the number - and then bring it into an array of a single index, which would be the integer link minus the last number. However, I’m not getting it. Because it’s returning like this on the console and I don’t understand why:

h,t,t,p,:,/,/,1,2,7,. ,0,. ,0,. ,1,:,5,5,0,0,/,r,e,d,i,r,e,c,t,. ,h,t,m,l,? ,r,e,d,i,r,e,c,t,=,1

Well, I’d like to know how I can resolve this in a simpler way. I am still beginner in programming and want to avoid these bad practices.

2 answers

4

An alternative, because it is a pattern that clearly repeats itself, would be to use Regex, because this way you can make the search more dynamic.

function redirection(link) {
  // Constrói o padrão que será utilizado na busca
  let pattern = /http:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.1:\d*\/quiz\.html(?:\?quiz=)?(\d*)?/i;
  // Realiza a busca no texto passado, retornando um array
  let grupos = link.match(pattern); // pattern => this.history

  if (grupos) {        
    let quiz = grupos[1] || 1;
    setTimeout(() => {
      console.log("Enviado", link);
      let result = `http://127.0.0.1:5500/quiz.html${ '?quiz='+ Number(++quiz) }`; 
      console.log("Retorno", result);
    }, 1000);
  } else {
    console.log("Invalido");
  }  
}


// Testando
let links = [
  'http://127.0.0.1:5500/quiz.html',
  'http://127.0.0.1:5500/quiz.html?quiz=1',
  'http://127.0.0.1:5500/quiz.html?quiz=2',
  'http://127.0.0.1:5500/quiz.html?quiz=3',
  'http://127.0.0.1:5500/quiz.html?quiz=10',
  'http://google.com'
];

links.forEach(l => redirection(l));

Another way to decrease the amount of code you write and thus decrease the size of your function is to make use of the new Features included since ES6.

2


As what changes in the URL are only the parameters of querystring, in your "quiz" example, you can extract the parameters and take the value of "quiz" and add 1, which is basically what it does in the various if.

There are many ways to do this, one simpler, which works well in more modern browsers is to use Urlsearchparams

This api parses the parameters of a URL, and allows you to use a method get to take a value, for example:

var urlParameters = new URL('http://127.0.0.1:5500/quiz.html').searchParams;
var quizParameter = urlParameters.get("quiz");

Return null, the parameter of querystring does not exist in the url, otherwise the value is returned, so for your example could make a if for the null condition, and then just add 1 to the "quiz" value, for example:

// testes:
console.log(obterProximaURL('http://127.0.0.1:5500/quiz.html'));
console.log(obterProximaURL('http://127.0.0.1:5500/quiz.html?quiz=9'));
console.log(obterProximaURL('http://127.0.0.1:5500/quiz.html?quiz=5'));
console.log(obterProximaURL('http://127.0.0.1:5500/quiz.html?quiz=2'));
console.log(obterProximaURL('http://127.0.0.1:5500/quiz.html?quiz=batatas'));
console.log(obterProximaURL('http://algumoutrolink.com'));


function obterProximaURL(url) {
   var urlBase = 'http://127.0.0.1:5500/quiz.html';
   // verifica se a url passada inicial com o template da "urlBase"   
   if (url.startsWith(urlBase)) {
      // valor inicial, caso não tenha o parâmetro "quiz"
      var quizNum = 1;
      // usando a API, pega os paramentros da query
      var urlParameters = new URL(url).searchParams;
      // obtém o parâmetro "quiz"
      var quizParameter = urlParameters.get('quiz');
      
      // se o parametro de quiz está presente, soma 1
      if (quizParameter != null) {
         quizNum = Number(quizParameter) + 1
      } 
      // retorna a nova URL. Se quizNum for NaN (não é um número), retorna apenas a URL
      return isNaN(quizNum)
             ? urlBase 
             : urlBase + '?quiz=' + quizNum;
      
   } else {
     // aqui trata caso a url não seja a esperada
     return "invalido";
   }
}

In your code just use grab the returned URL and set in window.location.href

  • 1

    It might be interesting to check for the case NaN also.

  • Thank you very much for your reply! :)

  • @Luizfelipe well noted, I added the reply thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.