Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
Correct way to toggle between two string values with ternary expression

I am trying to have a string that toggle between two values. I have declared as ternary

public position: string = (this.position == "positionOne" ? "positionOne" : "positionTwo");

What I would like to have a function for directly toggle from "positionOne" to "positionTwo" (value of the string). Something like `

togglePosition = function() 
     {this.position = !this.position}

and then it takes the opposite string as value. Or I need to do the complete evaluation also if declared as ternary? and then see if (position = "positionOne")... do whatever.. or else the upside down. You know what I mean? :) What solution you suggest to me?

Thanks a lot from now

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You could use an object and the keys as the wanted value.

function toggle(v) {
    return { positionOne: 'positionTwo', positionTwo: 'positionOne' }[v];
}
 
var position = 'positionOne';
console.log(position);
position = toggle(position);
console.log(position);
position = toggle(position);
console.log(position);

about 4 years ago · Santiago Trujillo Relatório

0

As an alternative you could use this (in cases where the values do not match "half-way"):

function toggle(pos) {
    return 'positionOnepositionTwo'.replace(pos, '');
}

pos = 'positionOne';
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));

Alternative with find

function toggle(pos) {
    return ['positionOne','positionTwo'].find(x => x !== pos);
}

pos = 'positionOne';
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));

about 4 years ago · Santiago Trujillo Relatório

0

Of course, you could use Array.find to do the same thing Nina mentioned:

var log = console.log;
function toggle(v) {
   return ['positionOne','positionTwo'].find(s=>s!=v);
}
 
var position = 'positionOne';
log( position );

position = toggle(position);
log( position );

position = toggle(position);
log( position );

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda