Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
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

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

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);

over 4 years ago · Santiago Trujillo Denunciar

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));

over 4 years ago · Santiago Trujillo Denunciar

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 );

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda