Skip to content

Instantly share code, notes, and snippets.

@vinodronold
Created March 13, 2020 03:38
Show Gist options
  • Save vinodronold/a11f98405b4bb164b358fcdd5b8d9765 to your computer and use it in GitHub Desktop.
Save vinodronold/a11f98405b4bb164b358fcdd5b8d9765 to your computer and use it in GitHub Desktop.
PeopleCode: This class provides a simple Hashtable implementation for storing and looking up Strings based on String keys
/*
This class provides a simple Hashtable implementation for storing and looking up Strings based on String keys
*/
class StringHashtable
method StringHashtable();
method Put(&key As string, &value As string);
method Get(&key As string) Returns string;
method GetKeys() Returns array of string;
method IsKey(&key As string) Returns boolean;
method GetValues() Returns array of string;
private
method GetKeyPosition(&key As string) Returns number;
instance array of string &keyArray;
instance array of string &valueArray;
end-class;
/*
Constructor
*/
method StringHashtable
/*Instantiate the arrays */
&keyArray = CreateArrayRept("", 0);
&valueArray = CreateArrayRept("", 0);
end-method;
/*
Put a value in the Hashtable. If the key already exists, it's value will be replaced with a new one .
*/
method Put
/+ &key as String, +/
/+ &value as String +/
Local number &nbr_pos = %This.GetKeyPosition(&key);
/**Check if a new entry is to be made or an old value has to be replaced **/
If (&nbr_pos <> - 1) Then
&keyArray [&nbr_pos] = &key;
&valueArray [&nbr_pos] = &value;
Else
&keyArray.Push(&key);
&valueArray.Push(&value);
End-If;
end-method;
/*
Get the value for a given key. Returns "" if no value is found .
*/
method Get
/+ &key as String +/
/+ Returns String +/
Local number &nbr_pos = %This.GetKeyPosition(&key);
If (&nbr_pos <> - 1) Then
Return &valueArray [&nbr_pos];
End-If;
Return "";
end-method;
/*
Returns the array of keys
*/
method GetKeys
/+ Returns Array of String +/
/**Return a clone of the array so that the original array cannot be tampered with **/
Return &keyArray.Clone();
end-method;
/*
Returns the array of values
*/
method GetValues
/+ Returns Array of String +/;
/**Return a clone of the array so that the original array cannot be tampered with **/
Return &valueArray.Clone();
end-method;
/*
Returns a bolean indicating if the provided String is a key or not
*/
method IsKey
/+ &key as String +/
/+ Returns Boolean +/
Local number &nbr_pos = %This.GetKeyPosition(&key);
If (&nbr_pos <> - 1) Then
Return True;
End-If;
Return False;
end-method;
/*
Returns the position in the array of the requested key. Will return -1 if the key is not present .
*/
method GetKeyPosition
/+ &key as String +/
/+ Returns Number +/
Local number &nbr_Len = &keyArray.Len;
Local number &i;
For &i = 1 To &nbr_Len
If (Exact(&key, &keyArray [&i])) Then
Return &i;
End-If;
End-For;
Return - 1;
end-method;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment