Empty set in javascript

烈酒焚心 提交于 2020-01-07 09:21:23

问题


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

回答1:


Best I have is

var isEmptyObject = function(v) { 
   for (x in v) {
     if (v.hasOwnProperty(x)) {
          return false;
     }
   } 
   return true;
};



回答2:


You can use Array for your task.

Or if you need to use special kind of operations on set you can define set as:

function SetOfValues(list) {
    if(!(this instanceof SetOfValues))
       return arguments.length===1?new SetOfValues(list):new SetOfValues;
    if(arguments.length===1)for(var i=0;i<list.length;i++)this[list[i]]=true;
}
SetOfValues.prototype.in=function(item) {
  return this.hasOwnProperty(item);
}
SetOfValues.prototype.empty=function() {
  for(var p in this)if(this.hasOwnProperty(p))return false;
  return true;
}

and then create and use set as:

var users = new SetOfValues(my_users);
// or with help of SetOfValues definition simply:
// var users = SetOfValues(my_users);
if(users.in(user)) allow_operation = true;
if(users.empty()||users.in(user)) allow_operation = true;


来源:https://stackoverflow.com/questions/7963882/empty-set-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!