Since JavaScript has no straight concept of a "set"...
Javascript does have a Set
object as of ES6. You can read about it here on MDN. And, there are multiple polyfills to use something similar in pre-ES6 environments.
If trying to simulate a Set
using a plain Javascript object, the key must be a string so you have to find a unique representation of your object that can be used as a string key. For a number, that's the string representation of the number, for a boolean, that's "true"
or "false"
. For an object, you have to create a unique string that represents the object and if the object is presented again you can recreate the same string. There are multiple possibilities for how to do that in pre-ES6. An ES6 set can hold an object directly without making a string representation of it.
Here's a related answer on using a Set-like object in pre-ES6: Mimicking sets in JavaScript?
And, a derivative of that that aims more for the ES6 Set interface here: https://github.com/jfriend00/ES6-Set.
In this ES6-like interface, there's a function called getKey()
here that illustrates a strategy for making a unique string key for many types of ES5 variables. You can see the details there.
As for what to set the data to in the Set, the best bet is to set it to the actual value of the data in the set because the key will be forced to be a string so you need to store the actual value somewhere. So, if the value isn't a string itself, then the actual value can be the value in the object.
Since the trues are dummy data, is there a better value to use? Maybe
one that only takes up 1 byte?
As for data size, exactly how Javascript variables are stored is an implementation detail that is not forced by a specification so it can vary from one implementation to another. Because a variable's type has to be part of the value, every variable has to have some sort of universal part of its value. You're not likely to find a value that is smaller than a simple boolean since a type that only has two possible values should be as small as possible already.
But, if you want to be able to tell the difference between a 3
and a "3"
stored in your set (e.g. you want them stored as separate items in the set), you will have to add a type modifier to the key so they are stored with separate keys and if you want to be able to get all the values from the set you will need to be able to reconstruct the original value. One simple way to get back to the original value is to store it as the value of the property on the object rather than just true
.