I have implemented a set datatype in javascript based in a generic object type, like this:
function createSetFromList(list) {
var set = { };
for (var i = 0; i < list.length; i++)
set[list[i]] = true;
return set;
}
Now I can easily check whether a given value belongs to the set:
var users = createSetFromList(my_users);
if (user in users) allow_operation = true;
The problem that I have is that I would like to check if my set is empty, like this:
if ("users is empty" or user in users) allow_operation = true;
But I have no idea how to check if the set is empty. I have tried with:
if (users == { } || user in users) allow_operation = true;
But apparently the first part of the logical expression is never true.
I guess it has to do with the fact that when users is empty, it is still initialized as an object, without any set elements, and an object is never equal to another object?
Is there any workaround to check for emptiness for my set implementation?
EDIT: I have tried out Malvolio's suggestion, and something strange is going on. I have modified it a bit to see what is happening:
function showProperties(v) {
for (x in v) {
if (v.hasOwnProperty(x)) {
$.log(x + " belongs");
} else {
$.log(x + " does not belong");
}
}
}
When running this:
showProperties(myset);
I always get only one line, regardless with which data my set has been initialized:
undefined belongs
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…