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