Implement a pseudo-hash table in Javascript

Source: Internet
Author: User
Tags hasownproperty

People who know the data structure should have heard of the hash table data structure. It is a typical non-linear structure that uses key-value pairs to store and retrieve data, it is also called the hash or collection method. In a general linear table structure, the relative positions of data are random, that is, there is no definite relationship between the data and the keywords used for retrieval. A series of comparisons are often required for data retrieval, finally, we find the data to be retrieved. This method is usually based on the cyclic comparison mechanism, which saves space at the cost of time and achieves the data storage and retrieval functions. A hash table uses key-value pairs for data storage, and establishes a one-to-one correspondence between the data storage location and Its keywords, therefore, each keyword corresponds to a unique storage location in the structure. Therefore, when retrieving data, you only need to quickly locate the data to be searched based on the corresponding relationship.

In fact, we usually do not care about how data is stored, but whether it is convenient for us to use data, such as sorting, searching, and replacing data, because this operation runs throughout the entire application, the efficiency requirement is very high. General advanced languages, such as C and C variants, provide data structures for storing hash tables. However, in weak languages such as javascript, it does not directly provide such a structure similar to a hash table, but we can start from an array and create a proprietary hash table data structure in script language based on the hash table principle.

We know that in the data, the corresponding data can be located directly through the subscript, that is, the space used to store the data. This attribute of the array determines that it can be used to implement the hash algorithm, however, in C language, the subscript of an array can only be an integer starting from 0, rather than other types of data. However, in javascript, we can use the concept of "object, simulate the hash algorithm based on the array features. In javascript, an object is actually a set of attributes or methods. Therefore, we can construct a Hashtable object, which has two attributes: key and value, write your own code to simulate a complete hash table. The following code implements a hash table in javascript:

1 function Hashtable ()
2 {
3 this. _ hash = {};
4 this. _ count = 0;
5 this. add = function (key, value)
6 {
7 if (this. _ hash. hasOwnProperty (key) return false;
8 else {this. _ hash [key] = value; this. _ count ++; return true ;}
9}
10 this. remove = function (key) {delete this. _ hash [key]; this. _ count --;}
11 this. count = function () {return this. _ count ;}
12 this. items = function (key) {if (this. contains (key) return this. _ hash [key];}
13 this. contains = function (key) {return this. _ hash. hasOwnProperty (key );}
14 this. clear = function () {this. _ hash = {}; this. _ count = 0 ;}
15}

It is easy to implement. We define a _ hash object in the function. This object has an attribute key. We can assign values to this attribute. The hasOwnProperty method is a method provided by javascript, returns whether the specified object contains an attribute. At the same time, we define a _ count object in this function to record the number of data in Hashtable, because we don't want to count every time we get the number of data in Hashtable through a built-in loop, this will reduce the overhead. As mentioned above, a basic feature of the hash algorithm is high efficiency. The delete statement is used in javascript to destroy an object.

The following are some examples of using this Hashtable:

1 var hashCompany = new Hashtable ();
2
3 // Add a key-value pair to Hashtable
4 function FillData (arr ){
5 hashCompany. clear ();
6
7 for (var I = 0; I <arr. length-1; I ++ ){
8 if (arr [I]! = ""){
9 t = arr [I]. split ("'");
10 if (t. length> 2 ){
11 if (! HashCompany. contains (t [0]. trim ())){
12 hashCompany. add (t [0]. trim (), t [1]);
13}
14}
15}
16}
17}
18
19 // traverse Hashtable and retrieve the value
20 function GetDataFromHash (){
21 var s;
22 if (hashCompany. count> 0 ){
23 for (var I in hashCompany. _ hash ){
24 s + = I + "| ";
25}
26}
27
28 if (s. length> 0 ){
29 s = s. substring (0, s. length-2 );
30}
31
32 return s;
33}

The code is relatively simple, so I will not add more details here. Here I use a trim function and I will add it below.

// Use regular expressions to remove spaces at both ends of the String. Anonymous functions are used to extend the String object.
String. prototype. trim = function () {return this. replace (/(^ \ s *) | (\ s * $)/g ,"");}

Hash Tables are frequently used in code. flexible use of hash tables can simplify Code and provide a lot of convenience, especially when storing data similar to arrays and hopefully facilitate retrieval. Save the code here for future use.

  1. Four rules for JavaScript function calls
  2. How to generate and compare hash values in Visual C #2005
  3. Replace methods and regular expressions in Javascript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.