tags:

views:

3566

answers:

6

What's the best way to calculate the length of a Dictionary object in Flex?

var d:Dictionary = new Dictionary();
d["a"] = "alpha";
d["b"] = "beta";

I want to check the length which should be 2 for this Dictionary. Is there any way to do it other than looping through the objects?

A: 

I'm fairly certain that there's either a length or count method in there... It's been awhile since I've done Flex, though.

Matt Grande
Not on Dictionary: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/Dictionary.html
secoif
+5  A: 

No, there is no way to check the length of an object(Dictionary is pretty much an object that supports non-String keys) other than looping through the elements.

http://www.flexer.info/2008/07/31/how-to-find-an-objects-length/

You probably don't have to worry about checking if the property is an internal one.

CookieOfFortune
Here is the code to loop as notbody else provided it:'[ public static function getLen(d:Dictionary):int { var i:int = 0; for (var key:Object in d) { i++; } return i; }]
Donal Tobin
+1  A: 

You can use associative arrays instead because I don't think it's possible to check the length of a Dictionary object. You could however extend the Dictionary class and add that functionality and override the corresponding methods.

Alternatively, you could loop through it each time to get the length which isn't really a good idea but is available.

var d:Dictionary = new Dictionary();
d["hi"] = "you"
d["a"] = "b"
for (var obj:Object in d) {
  trace(obj);
}
// Prints "hi" and "a"

You can also look here for information on using the "setPropertyIsEnumerable" but I believe that's more useful for objects than it is for Dictionary.

nevets1219
A: 

You could write a class around a dictionnary that controls insertions/removals so you can keep track of the key count.

Try extending proxy or just do a wrapper.

tousdan
+2  A: 

There's a util function in as3corelib which can get the keys in the dictionary. You can check out DicitonaryUtil

The method is:

 public static function getKeys(d:Dictionary):Array
 {
  var a:Array = new Array();

  for (var key:Object in d)
  {
   a.push(key);
  }

  return a;
 }

So you would do getKeys(dictionary).length

marketer
This actually cretes an array and adds each element to it so this is very expensive to do (in memory and time)
Donal Tobin
A: 

For anyone stumbling upon this now there is an update to DictionaryUtil. You can now just call..

var count:int = DictionaryUtil.getKeyCount(myDictionary);
Do you have information about when this became available or a link to documentation? There's not much information out there about this.
calvinf
No I don't. I know that it's available in Flex 3.5 and in 4, probably even as far back as 3. I was just looking for this answer and someone on here mentioned DictionaryUtil so I did auto-complete on the functions available in it and stumbled upon this.