Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit19105e2

Browse files
committed
Hash Table data structure
A hash table is a data structure used to implement an associativearray, that can map keys to values. A hash table uses a hash functionto compute an index into an array of buckets or slots, from which thecorrect value can be found. The idea is to access a value in O(1).
1 parentfcd2b07 commit19105e2

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

‎src/data-structures/hash-table.js

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* Hash Table
3+
*
4+
* An associative array, that can map keys
5+
* (strings and numbers) to values in O(1).
6+
*
7+
*@example
8+
* var hash = require('path-to-algorithms/src/data-structures'+
9+
* '/hash-table');
10+
* var HashTable = new hash.HashTable();
11+
*
12+
* HashTable.put(10, 'value');
13+
* HashTable.put('key', 10);
14+
*
15+
* console.log(HashTable.get(10)); // 'value'
16+
* console.log(HashTable.get('key')); // 10
17+
*
18+
* HashTable.remove(10);
19+
* HashTable.remove('key');
20+
*
21+
* console.log(HashTable.get(10)); // 'undefined'
22+
* console.log(HashTable.get('key')); // 'undefined'
23+
*
24+
*@module data-structures/hash-table
25+
*/
26+
(function(exports){
27+
'use strict';
28+
29+
exports.HashTable=function(){
30+
this.elements=[];
31+
};
32+
33+
exports.HashTable.prototype.hashCode=function(str){
34+
vari;
35+
varhashCode=0;
36+
varcharacter;
37+
38+
if(str.length===0){
39+
returnhashCode;
40+
}
41+
42+
for(i=0;i<str.length;i+=1){
43+
character=str.charCodeAt(i);
44+
hashCode=((hashCode<<5)-hashCode)+character;
45+
hashCode=hashCode&hashCode;
46+
}
47+
48+
returnhashCode;
49+
};
50+
51+
exports.HashTable.prototype.put=function(key,value){
52+
varhashCode=this.hashCode(key);
53+
this.elements[hashCode]=value;
54+
};
55+
56+
exports.HashTable.prototype.get=function(key){
57+
varhashCode=this.hashCode(key);
58+
returnthis.elements[hashCode];
59+
};
60+
61+
exports.HashTable.prototype.remove=function(key){
62+
varhashCode=this.hashCode(key);
63+
this.elements.splice(hashCode,1);
64+
};
65+
})(typeofwindow==='undefined' ?module.exports :window);

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp