-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.php
More file actions
92 lines (75 loc) · 2.14 KB
/
HashTable.php
File metadata and controls
92 lines (75 loc) · 2.14 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
namespace Zubs\Dsa\HashTable;
use Zubs\Dsa\Trie\TrieNode;
class HashTable
{
private array $table = [];
private int $size = 0;
/**
* Creates a unique hash to use
* @param string $key User provided key
* @return string Hashed key
*/
private function hash(string $key): string
{
return hash('md5', $key);
}
/**
* Store a key value pair in the hash table
* @param string $key Key to store
* @param string|int $value Value to store
* @return string|int Returns the input value
*/
public function set(string $key, string | int $value): string | int
{
$index = $this->hash($key);
$this->table[$index] = $value;
$this->size += 1;
return $value;
}
public function setChildTrie(string $key, TrieNode $node): TrieNode
{
$index = $this->hash($key);
$this->table[$index] = $node;
$this->size += 1;
return $node;
}
/**
* Fetch a stored value from the hash table
* @param string $key Key to search for
* @return string|int|null Returns null or stored value
*/
public function get(string $key): string | int | null
{
$index = $this->hash($key);
return array_key_exists($index, $this->table) ? $this->table[$index] : null;
}
public function getChildTree(string $key): TrieNode | null
{
$index = $this->hash($key);
return array_key_exists($index, $this->table) ? $this->table[$index] : null;
}
/**
* Delete a stored value from the hash table
* @param string $key Key to delete
* @return string|int|null Returns null or deleted value
*/
public function remove(string $key): string | int | null
{
$index = $this->hash($key);
if (!array_key_exists($index, $this->table)) {
return null;
}
$value = $this->table[$index];
unset($this->table[$index]);
$this->size -= 1;
return $value;
}
/**
* @return int Returns number of items in the hash table
*/
public function getSize(): int
{
return $this->size;
}
}