AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1443&pId=-1
CodeSnip: KeyValuePair, Not Just a .NET Thing
page
by Ryan Scott
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 15335/ 22

Introduction

The KeyValuePair class defines a key/value pair that can be set or retrieved. This class proves to be beneficial under many circumstances, why should these benefits stop here?

It is too often that JavaScript developers find themselves delimiting two values to retain an object’s state or pretend to have a struct. And that is exactly what this class does.

Listing 1   

function KeyValuePair()
{
  this._strKey = (arguments.length == 2) ? arguments[0]: null;
  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.

Listing 2

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));
Conclusion

In this article we demonstrated how to implement Microsoft’s KeyValuePair structure in a JavaScript environment.



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-19 3:05:24 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search