Obiwahn
Obiwahn

Reputation: 3087

How to toggle through states?

I search for a short and readable way to toggle through states.

E.g. gender states: m -> f -> n

Right now I use either

if (this.gender === "m") this.gender = "f";
    else if (this.gender === "f") this.gender = "n";
    else this.gender = "m";

or

this.gender = this.gender === "m" ? "f" : this.gender === "f" ? "n" : "m";

Both are horrible. Am I missing something?

Upvotes: 0

Views: 57

Answers (3)

Andre
Andre

Reputation: 788

This is a really fun question actually, here's some methods that come to mind:

Using a String and offsetting:

var genderpath = "mfn";

gender = genderpath[(genderpath.indexOf(gender)+1)%genderpath.length];

Using an object:

var genders = {'m': 'f', 'f': 'n', 'n': 'm'};

gender = genders[gender];

Using a combination of solutions(probably the best):

var genderpath = "mfnm";

gender = genderpath[genderpath.indexOf(gender)+1];

Upvotes: 1

Benjamin Eckardt
Benjamin Eckardt

Reputation: 728

You could use a mapping table:

const mapping = {
    'm': 'f',
    'f': 'n',
    'n': 'm',
}

and use it as such:

this.gender = mapping[this.gender];

// Edit My another solution was already provided by @VRoxa in the meantime.

Upvotes: 4

VRoxa
VRoxa

Reputation: 1051

Well, another shorter but also cryptic way of doing this would be iterating through an ordered array.

const genders = [ 'm', 'f', 'n' ];
let index = 0;

const toggle = () =>
  genders[(++index) % 3];

Even you could define handlers for different iterations

const genders = [ 'm', 'f', 'n' ];

const toggleHandler = () => {
  let index = 0;
  return () => genders[(++index) % 3];
}

const toggle = toggleHandler();

// Decice whether you want to increment
// then return or vice-versa
console.log(toggle()); // f
console.log(toggle()); // n
console.log(toggle()); // m
console.log(toggle()); // f

Hope it helps.

Upvotes: 1

Related Questions