HTML and CSS Reference
In-Depth Information
Optimizing Long Lists Of Yes/No Values With
JavaScript
BY LEA VEROU
Very frequently in Web development (and programming in general), you need to store a long
list of boolean values (yes/no, true/false, checked/unchecked… you get the idea) into
something that accepts only strings. Maybe it's because you want to store them in
localStorage or in a cookie, or send them through the body of an HTTP request. I've needed
to do this countless times.
The last time I stumbled on such a case wasn't with my own code. It was when Christian
Heilmann showed me his then new slide deck , with a cool feature where you could toggle
1
2
the visibility of individual slides in and out of the presentation. On seeing it, I was impressed.
Looking more closely, though, I realized that the checkbox states did not persist after the page
reloaded. So, someone could spend a long time carefully tweaking their slides, only to
accidentally hit F5 or crash their browser, and then—boom!—all their work would be lost.
Christian told me that he was already working on storing the checkbox states in
localStorage . Then, naturally, we endlessly debated the storage format. That debate inspired
me to write this chapter, to explore the various approaches in depth.
Using An Array
We have two (reasonable) ways to model our data in an array. One is to store true/false
values, like so:
[ false , true , true , false , false , true , true ]
The other is to store an array of 0s and 1s, like so:
[ 0 , 1 , 1 , 0 , 0 , 1 , 1 ]
Whichever solution we go with, we will ultimately have to convert it to a string, and then
convert it back to an array when it is read. We have two ways to proceed: either with the old
Array#join() (or Array#toString() ) and String#split() , or with the fancier
JSON.stringify() and JSON.parse() .
 
Search WWH ::




Custom Search