Creating KeyValue Pair collection in JavaScript
By [)ia6l0 iii
'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));
Popularity (3948 Views)
Article Discussion: Creating KeyValue Pair collection in JavaScript
[)ia6l0 iii posted at Thursday, October 23, 2008 10:02 AM
Superb Article.
Hi!
I watched these kind of Function in .Net. This is the First time i'm watching in JavaScript. Very Nice Article and Used to Improve My Javascript Knowledge.
Thank U a LOT.......
thanks.
[)ia6l0 iii replied
to Er Suresh Ganesan at Thursday, October 23, 2008 7:10 PM
end of post