@violangreg/

building a HashTable

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class HashTable {
  constructor(size){
    this.data = new Array(size);
  }

  _hash(key) {
    let hash = 0;
    for (let i = 0; i < key.length; i++){
        hash = (hash + key.charCodeAt(i) * i) % this.data.length
    }
    return hash;
  }

  set(key, value) {
    //check input
    if(!(typeof key === "string"))
      return;

    let address = this._hash(key);
    
    if(!this.data[address]){
      this.data[address] = new Array();
    }

    let bucket = {
      key: key,
      value: value
    };

    this.data[address].push(bucket);
  }

  get(key) {
    if(!(typeof key === "string"))
      return;

    const buckets = this.data[this._hash(key)];
    for(var i in buckets)
    {
      if(buckets[i].key == key)
        return buckets[i].value;
    }
  }

  keys(){
    let keys = new Array();

    for(var i in this.data) {
      for(var j in this.data[i]) {
        if(this.data[i])
          keys.push(this.data[i][j].key);
      }
    }
    return keys;
  }

}

const myHashTable = new HashTable(50);
myHashTable.set("grapes", 10000);
myHashTable.set("apple", 33);
myHashTable.get("apple");




Native Browser JavaScript