Creating KeyValue Pair collection in JavaScript

'KeyValuePair' is a generic class that is available in .Net Framework versions 2.0 and above. It provides many functions as a collection. Javascript needs this for the very purpose it serves.

The KeyValuePair can be defined as follows. 

//KeyValuePair function
function KeyValuePair()
{

  'Assigning the Key from the arguments
  this._strKey = (arguments.length == 2) ? arguments[0]: null;
  'Assigning the Key from the arguments
  this._strValue = (arguments.length == 2) ? arguments[1]: null;
 
  // if parameter is defined, the key is set.
  // if parameter is not defined, the key is retrieved.
  this.Key = function()
  {
    if (arguments.length == 1)
      this._strKey = arguments[0];
    else
      return this._strKey;
  }
  // if parameter is defined, the value is set.
  // if parameter is not defined, the value is retrieved.
  this.Value = function()
  {
    if (arguments.length == 1)
      this._strValue = arguments[0];
    else
      return this._strValue;
  }
  // Params: (KeyValuePair objkvp)
  // Return: boolean
  this.Equals = function(oKV)
  {
    try
    {
      if (oKV.GetType() == this.GetType())
      {
        if (this._strKey == oKV.Key() && this._strValue == oKV.Value())
        {
          return true;
        }
      }
    }
    catch (e)
    {
      throw "(Exception: kvp_e0) Invalid parameter type";
    }
    return false;
  }
  // Return: string
  this.GetType = function()
  {
    return "Library.KeyValuePair";
  }
  // Return: string (delimits the key and value if provided)
  this.ToString = function()
  {
    var strDelimiter = (arguments.length == 1) ? arguments[0]: "";
    return this._strKey + strDelimiter + this._strValue;
  }
}

//Below are some examples of how to use this class. var oKeyValue1 = new KeyValuePair(); oKeyValue1.Key("Name"); oKeyValue1.Value("Ryan"); var oKeyValue2 = new KeyValuePair("Name", "Jason"); // Are they equal? alert(oKeyValue1.Equals(oKeyValue2)); // Look inside alert(oKeyValue1.ToString()); alert(oKeyValue1.ToString(":")); // Get type alert(oKeyValue1.GetType()); alert(oKeyValue1.GetType() == oKeyValue2.GetType()); // Change oKeyValue1.Value("Jason"); // Show they are equal alert(oKeyValue1.Equals(oKeyValue2));
By [)ia6l0 iii   Popularity  (5049 Views)