Skip to content
Daniel Gimenez edited this page Jul 26, 2013 · 11 revisions

The performance of using object literals as associative arrays is poor. If performance is an issue, use this class to create associative arrays instead.

It is located at \Scripts\DataStructures\dgAssociativeArray-1.0.0.js

Members

Constructor

The constructor has one optional parameter, initalKeyValueArray. This can either by of the type dgAssociativeArray or of the type Array. If it is an array, each element should be an object with the properties key and value.

Properties

The following are intended to be read only properties.

  • values: an array of all values for the instance
  • keys: an array of all keys for the instance.
  • length: number of items for the instance.

Methods

  • empty(): removes all items from the array.
  • indexOf(key): finds the index of a given key.
  • add(key, value): adds an item and returns the new index. Will add new instances of the same key if one already exists.
  • addMany(keyValueArray): Either a dgAssociativeArray or an Array with objects that have the properties key and value.
  • set(key, value): Sets the value at the first instance of the given key. Creates a new element if one does not already exist. Use this instead of add to ensure that only one key exists.
  • get(key): Returns the first value of a given key.
  • getAt(index): returns key-value pair object ({ key, value }) for the element at index.
  • insert(index, key, value): inserts an element at the given index, displacing all elements after by one. If the index is out of bounds then false is returned, otherwise true.
  • remove(key): removes the first item with a given key.
  • removeAt(index): removes item at given index. Returns key-value pair of removed item.
  • toKeyValueArray(): Returns array representation of this object with each element being a key-value pair object.
  • toString([maxItems = 20]): Returns the string representation of the object. If maxItems is passed that number of items is included in the string followed by an ellipses indicating further elements.
  • resetEnumerator(): Resets the internal enumerator index to the start of the array.
  • next(): Gets the next item in the array. Returns key-value pair.

Usage

    // create new array
    var myArray = new dgAssociativeArray();

    myArray.add('kiddo', { barks: true, fluffy: false });
    myArray.add('misocio', { barks: false, fluffy: true });

    // add many items
    myArray.addMany([
        { key: 'marley', { barks: true, fluffy: true } },
        { key: 'shaggy', { barks: true, fluffy: true } },
    ]);

    // loop through pets
    var myPet;
    while (myPet = myArray.next()) {
        if (myPet.value.fluffy) {
            console.log(myPet.key + ' is very fluffy.');
        }
    }

Clone this wiki locally