smart javascript state toggle
I'd like to share a simple construct that will make your code more concise and allow you to get rid of some if statements.
Let's assume we have two states and we want to switch between them. If current state is A then we want to switch to B and vice versa - from B switch to A. The traditional code for that would be:
if (state == 'A') {
state = 'B'
} else if (state == 'B') {
state = 'A'
} else {
state = undefined;
}
A tricky way to achieve it is:
var toggle = {'A': 'B', 'B': 'A'};
state = toggle[state];
I guess such construct works not only in javascript but also in several other languages.
Written by Łukasz Wiktor
Related protips
2 Responses
var toggle = {'a':'b', 'b':'c', 'c':'a'}
would give me three states. Lovely.
over 1 year ago
·
That's a state machine there :P
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#