what is the hashmap like in php

Solutions on MaxInterview for what is the hashmap like in php by the best coders in the world

showing results for - "what is the hashmap like in php"
Mia
11 Aug 2018
1class IEqualityComparer {
2    public function equals($x, $y) {
3        throw new Exception("Not implemented!");
4    }
5    public function getHashCode($obj) {
6        throw new Exception("Not implemented!");
7    }
8}
9
10class HashMap {
11    private $map = array();
12    private $comparer;
13
14    public function __construct(IEqualityComparer $keyComparer) {
15        $this->comparer = $keyComparer;
16    }
17
18    public function has($key) {
19        $hash = $this->comparer->getHashCode($key);
20
21        if (!isset($this->map[$hash])) {
22            return false;
23        }
24
25        foreach ($this->map[$hash] as $item) {
26            if ($this->comparer->equals($item['key'], $key)) {
27                return true;
28            }
29        }
30
31        return false;
32    }
33
34    public function get($key) {
35        $hash = $this->comparer->getHashCode($key);
36
37        if (!isset($this->map[$hash])) {
38            return false;
39        }
40
41        foreach ($this->map[$hash] as $item) {
42            if ($this->comparer->equals($item['key'], $key)) {
43                return $item['value'];
44            }
45        }
46
47        return false;
48    }
49
50    public function del($key) {
51        $hash = $this->comparer->getHashCode($key);
52
53        if (!isset($this->map[$hash])) {
54            return false;
55        }
56
57        foreach ($this->map[$hash] as $index => $item) {
58            if ($this->comparer->equals($item['key'], $key)) {
59                unset($this->map[$hash][$index]);
60                if (count($this->map[$hash]) == 0)
61                    unset($this->map[$hash]);
62
63                return true;
64            }
65        }
66
67        return false;
68    }
69
70    public function put($key, $value) {
71        $hash = $this->comparer->getHashCode($key);
72
73        if (!isset($this->map[$hash])) {
74            $this->map[$hash] = array();
75        }
76
77        $newItem = array('key' => $key, 'value' => $value);        
78
79        foreach ($this->map[$hash] as $index => $item) {
80            if ($this->comparer->equals($item['key'], $key)) {
81                $this->map[$hash][$index] = $newItem;
82                return;
83            }
84        }
85
86        $this->map[$hash][] = $newItem;
87    }
88}