ActionScript 3 MultiMap Class

Written on June 10, 2007 – 5:28 pm | by sascha |

Recently I needed a HashMap for a project to map key/value pairs but in that particular case the Map required to map not just one but several values to a key. I could have used an array or object to store the values in and map that one but in practice it turned out that accessing the map looked rather messy. It would be much more elegant to have a map to that multiple values can be mapped directly. After some investigation (strangely even Java seems not to have a MultiMap included) I came up with writing my own MultiMap class, so here it is!


The MultiMap is heavily based on Michael Baczynski’s HashTable class but I modified it to my requirements and added a couple of additional methods for luxury. At first I wrote an even more customized version that would decide automatically which hash function to use but as it turned out some of these changes weighted heavy on the performance, especially not using a strict equality operator (===) and having a HashEntry object with non-numeric keys. In fact Michael’s class is still a tad faster (he really squeezed out the last bit of performance there) but as long as the MultiMap isn’t too large/full there is only a minor difference of some milliseconds.
As a trade-off I added checking for existing keys (which can be omitted to improve performance when adding values) and of course there is the multiple values functionality which required a more complex implementation of some methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/*
 * MultiMap.as v1.1 - ActionScript 3.0 MultiMap Data Structure
 * written by Sascha Balkau - http://www.hiddenresource.net/
 * Based on Michael Baczynski's HashTable class.
 *
 * ``The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 */
package com.hexagonstar.data.structures.maps
{
	/**
	 * A MultiMap works similar like a HashMap but let's the user map more
	 * than one value to a key where the HashMap only allows one value
	 * per key.
	 * Mapped values can be fetched with the getValue method either returning
	 * an Array that contains all values that are mapped to the key or only
	 * one of the values defined by the valueIndex argument.
	 *
	 * @example
	 *    // Creating a MultiMap with a size of 10000:
	 *    _multiMap = new MultiMap(100000, MultiMap.hashInt);
	 *    // Mapping values to the map:
	 *    _multiMap.put(1000, "valueA_0", "valueB_0", "valueC_0", "valueD_0");
	 *    _multiMap.put(1001, "valueA_1", "valueB_1", "valueC_1", "valueD_1");
	 *    _multiMap.put(1002, "valueA_2", "valueB_2", "valueC_2", "valueD_2");
	 *    // Fetching "valueC_1":
	 *    var result:String = _multiMap.getValue(1001, 2);
	 */
	public class MultiMap
	{
		// Properties /////////////////////////////////////////////////////////////////
 
		/** @private */
		private var _map:Array;
		/** @private */
		private var _size:int;
		/** @private */
		private var _divisor:int;
		/** @private */
		private var _count:int;
		/** @private */
		private var _hash:Function;
		/** @private */
		private var _noDupeCheck:Boolean;
 
		// Constructor ////////////////////////////////////////////////////////////////
 
		/**
		 * Constructs a new MultiMap instance.
		 *
		 * @param size The size that the MultiMap should have.
		 * @param hashFunction The hashing function used for the MultiMap.
		 *        Use either MultiMap.hashString or MultiMap.hashInt for
		 *        this depending on the type of key used.
		 * @param allowDuplicates Normally the MultiMap does not allow to have duplicate
		 *        keys in it but if it can be assured that all provided keys are
		 *        unique this argument can be set to true which results in a faster
		 *        execution when adding new entries to the map with put().
		 */
		public function MultiMap(size:int, hashFunction:Function, noDupeCheck:Boolean = false)
		{
			_size = size;
			_hash = hashFunction;
			_noDupeCheck = noDupeCheck;
			clear();
		}
 
		// Hash Functions /////////////////////////////////////////////////////////////
 
		/**
		 * Returns a hashcode for the specified key.
		 *
		 * @return An Integer that can be used as a hash for the MultiMap.
		 */
		public static function hashString(key:String):int
		{
			var result:int = 0;
			var len:int = key.length;
			for (var i:int = 0; i < len; i++)
			{
				result += (i + 1) * key.charCodeAt(i);
			}
			return result;
		}
 
		/**
		 * A simple function for hashing integers.
		 *
		 * @return An Integer that can be used as a hash for the MultiMap.
		 */
		public static function hashInt(key:int):int
		{
			return hashString("" + key);
		}
 
		// Query Operations ///////////////////////////////////////////////////////////
 
		/**
		 * Returns the amount of mappings that the map contains.
		 *
		 * @return The amount of mappings in the map.
		 */
		public function size():int
		{
			return _count;
		}
 
		/**
		 * Returns whether the map contains any mappings or not.
		 *
		 * @return true If the map contains any mappings otherwise false.
		 */
		public function isEmpty():Boolean
		{
			return (size() < 1);
		}
 
		/**
		 * Returns the value that is mapped to the specified key and at the
		 * specified valueIndex. If no valueIndex is specified always an
		 * Array is returned that contains all values that are mapped to the
		 * specified key, no matter if only one or several values were mapped.
		 * If the valueIndex is larger than the resulting array's length
		 * undefined is returned instead.
		 *
		 * @param key The key to return the mapped value(s) for.
		 * @param valueIndex The index in the resulting values array from
		 *        which a single value should be returned. If this argument
		 *        is omitted all mapped values are returned as an array.
		 * @return Either an array containing all values mapped to the key
		 *         or the specific value that exists at valueIndex or
		 *         undefined if the valueIndex is out of range.
		 */
		public function getValue(key:*, valueIndex:int = -1):*
		{
			if (valueIndex < 0) return getValues(key);
 
			var list:Array = _map[int(_hash(key) & _divisor)];
			var len:int = list.length;
 
			for (var i:int = 0; i < len; i++)
			{
				var entry:HashEntry = list[i];
				if (entry.key === key) return entry.data[valueIndex];
			}
			return null;
		}
 
		/**
		 * Returns an array with all values that are mapped to the specified key.
		 *
		 * @param key The key to return the mapped values for.
		 * @return An array that contains all values that are mapped to the key.
		 */
		public function getValues(key:*):Array
		{
			var list:Array = _map[int(_hash(key) & _divisor)];
			var len:int = list.length;
 
			for (var i:int = 0; i < len; i++)
			{
				var entry:HashEntry = list[i];
				if (entry.key === key)
				{
					return entry.data;
				}
			}
			return null;
		}
 
		/**
		 * Checks whether the MultiMap contains the specified key.
		 *
		 * @param key The key to check for existance in the map.
		 * @return true if the specified key exists in the MultiMap
		 *         otherwise false.
		 */
		public function containsKey(key:*):Boolean
		{
			var list:Array = _map[int(_hash(key) & _divisor)];
			var len:int = list.length;
 
			for (var i:int = 0; i < len; i++)
			{
				var entry:HashEntry = list[i];
				if (entry.key === key) return true;
			}
			return false;
		}
 
		/**
		 * Checks in the MultiMap if it contains the specified value and
		 * returns the mapped key of the first successful search result
		 * it finds or returns -1 if the value wasn't found in the map.
		 *
		 * @param value The value to be checked for availability in the map.
		 * @return A number containing the key that the first successful
		 *         search result is mapped to or -1 if the value was not
		 *         found in the map.
		 */
		public function containsValue(value:*):int
		{
			for (var i:int = 0; i < _size; i++)
			{
				var list:Array = _map[i];
				var len:int = list.length;
				for (var j:int = 0; j < len; j++)
				{
					var entry:HashEntry = list[j];
					var l:int = entry.data.length;
					for (var e:int = 0; e < l; e++)
					{
						if (entry.data[e] === value) return entry.key;
					}
				}
			}
			return -1;
		}
 
		/**
		 * Returns an associative array that contains the keys and
		 * values of the MultiMap. The resulting array contains objects
		 * with fields 'key' and 'data'. The data field contains an array
		 * with all values that were mapped to the key.
		 *
		 * @param sort If set to true the resulting array will be sorted
		 *        on the 'key' field.
		 * @return An associative array that contains the keys and
		 *         values of the MultiMap.
		 */
		public function toArray(sort:Boolean = false):Array
		{
			var result:Array = new Array();
			for (var i:int = 0; i < _size; i++)
			{
				var list:Array = _map[i];
				var len:int = list.length;
				if (len > 0)
				{
					for (var j:int = 0; j < len; j++)
					{
						var entry:HashEntry = list[j];
						result.push({key: entry.key, data: entry.data});
					}
				}
			}
			return (sort) ? result.sortOn("key") : result;
		}
 
		/**
		 * Returns a string representation of the MultiMap.
		 *
		 * @return A string representation of the MultiMap.
		 */
		public function toString():String
		{
			return "[MultiMap, size=" + size() + "]";
		}
 
		/**
		 * Returns a string representing the MultiMap's structure.
		 * Used for debugging purposes.
		 *
		 * @return A string representing the MultiMap's structure.
		 */
		public function dump():String
		{
			var result:String = "nMultiMap:n";
			for (var i:int = 0; i < _size; i++)
			{
				var list:Array = _map[i];
				var len:int = list.length;
				var idt:String = "";
				if (len > 0)
				{
					result += i + ".n";
					for (var j:int = 0; j < len; j++)
					{
						if (j < 10) idt = "  ";
						else if (j < 100) idt = " ";
						var entry:HashEntry = list[j];
						result += "t" + idt + j + ". " + "key:" + entry.key
							+ "t[" + entry.data + "]n"
					}
				}
			}
			return result;
		}
 
		// Modification Operations ////////////////////////////////////////////////////
 
		/**
		 * Maps a key/values couple into the MultiMap. The key must be a string
		 * or a positive integer for the MultiMap to work correctly. The value(s)
		 * can be of any type. If the specified key already exists in the map, the
		 * values on the key are replaced with the new values and true is returned.
		 * If the key didn't exist in the map false is returned.
		 *
		 * @param key A string or integer that acts as a key to map the value(s) with.
		 * @param values A list of values that can be mapped to the given key.
		 * @return true if the specified key already exists in the map and it's
		 *         values were replaced with the new ones, otherwise false is returned.
		 */
		public function put(key:*, ... values):Boolean
		{
			var pos:int = _hash(key) & _divisor;
 
			// Check for duplicate keys by default. If a dupe key is
			// found, replace it's value(s) with the new ones:
			if (!_noDupeCheck)
			{
				var list:Array = _map[pos];
				var len:int = list.length;
				for (var i:int = 0; i < len; i++)
				{
					var entry:HashEntry = list[i];
					if (entry.key === key)
					{
						entry.data = values;
						return true;
					}
				}
			}
 
			_map[pos].push(new HashEntry(key, values));
			_count++;
			return false;
		}
 
		/**
		 * Removes the values from the MultiMap that are mapped with the specified
		 * key or if a valueIndex larger than -1 was specified removes only the
		 * value at the given index from the mapped key.
		 *
		 * @param key The key from which to remove the mapped value(s) from.
		 * @param valueIndex The index in the resulting values array from
		 *        which a single value should be removed. If this argument
		 *        is -1 or smaller all mapped values are removed.
		 * @return Either an array containing all removed values mapped to the
		 *         key or the specific value that existed at valueIndex or
		 *         undefined if the valueIndex is out of range.
		 */
		public function remove(key:*, valueIndex:int = -1):*
		{
			var list:Array = _map[int(_hash(key) & _divisor)];
			var len:int = list.length;
			var result:*;
 
			for (var i:int = 0; i < len; i++)
			{
				var entry:HashEntry = list[i];
				if (entry.key === key)
				{
					if (valueIndex > -1)
					{
						result = entry.data[valueIndex];
						entry.data.splice(valueIndex, 1);
						return result;
					}
					else
					{
						result = entry.data;
						list.splice(i, 1);
						_count--;
						return result;
					}
				}
			}
			return null;
		}
 
		// Bulk Operations ////////////////////////////////////////////////////////////
 
		/**
		 * Clears all mappings from the map. The map will be empty after this call.
		 */
		public function clear():void
		{
			_map = new Array(_size);
			for (var i:int = 0; i < _size; i++)
			{
				_map[i] = [];
			}
			_divisor = _size - 1;
			_count = 0;
		}
	}
}
 
/**
 * Container class for storing key/data couples.
 */
internal class HashEntry
{
	public var key:int;
	public var data:Array;
 
	public function HashEntry(key:int, data:Array)
	{
		this.key = key;
		this.data = data;
	}
}

I’m sure there is still a lot of room for improvement so if you have any suggestions it would be cool to let us know!

11 Responses to “ActionScript 3 MultiMap Class”

  1. Michael says:

    Nice work :-) Perhaps I would add a function that just retrieves all stored values at a given key perhaps like so:


    public function getValues(key:*):Array
    {
    ...
    for (...)
    {
    if (entry.key === key)
    {
    return entry.data;
    }
    }
    return null;
    }

    This would be a a little bit faster when often processing a bunch of values at a key.

  2. Michael says:

    ah I forgot to mention, when you omit the valueIndex parameter in the getValue() function and the entry has multiple items you don’t know if the function returns an array or an object/primitive. Maybe it would be better to always return an array (even if it contains only one item) or feed it with an empty array and the function fills out the array elements and instead returns the number of items:

    var data:Array = [];
    var numItems:int = getValues(myKey, []);

  3. sascha says:

    Hi Michael, adding a getValues method that always returns an array is a good idea. But it makes me thinking about if in that case changing the getValue method to always return an array makes sense. If the user doesn’t provide a valueIndex an Array should always be expected so how about this …
    Adding the getValues method and in the getValue method at the beginning use this:

    if (valueIndex < 0) return getValues(key);

    That way always an Array is returned if valueIndex was omitted. But then again it is questionable if valueIndex should be an optional or obligatory parameter.
    Interesting to mention that your find method is still faster than the getValues method even though they are virtually the same. In fact typing the entry variable inside the for loop provides a small performance boost for my method.

  4. [...] MultiMap ist eine Erweiterung der Hash-Tabelle von polygonal. [...]

  5. Eduardo says:

    Hey! Thxs for the reply!

    I think I gave the wrong mail now it’s the correct! thanxS!!!

  6. Gaston says:

    how do i implement it? can i see an example? tk.

  7. Sascha says:

    Gaston, there’s an example of how to use it in the class comment. Or did you mean something else?

  8. Randall Salas says:

    Hi All:
    I wonder if next thing if possible:
    If more than one key is accepted, it will return values based on:
    Key1, key2, key3, etc.

    And if just one key is entered, it should return all values that match that key.

    Thx.

    Randall

  9. Sev says:

    Hmm.. looking through your code makes me wonder why you don’t use hash tables to store the array hash/map? I usually do sth like that (shortened, simplified):

    _map : Object;

    function setValue( key : String , value : * ) : void {
    if ( _map[key] == undefined ) _map[key] = [];
    _map[key].push(value);
    }

    That way you don’t have to iterate through all lists which is MUCH faster. All methods in your class would be feasible with that data structure (I think). Or is there sth I’m not getting? :)

  10. sascha says:

    Sev, yes thanks for the tip. I might be rewriting the class anyway soon so I will try using tables.

Leave a Reply

Welcome to H1DD3N.R350URC3!

These are the adventures of a random guy trying to be an independant game developer, utilizing ActionScript for programming and talking abouting gaming and nonsense in general.

Need any news feed?

 Main Feed (contains all categories), Dev Feed, Design Feed, Audio Feed, Gaming Feed, Miscellaneous Feed
Find entries: