-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCounter.php
More file actions
90 lines (76 loc) · 1.8 KB
/
Counter.php
File metadata and controls
90 lines (76 loc) · 1.8 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
<?php
namespace Babanesma\DataStructures\Collections;
use OutOfRangeException;
/**
* Counter map
*
* Holds the count of each object, Objects are unique.
* Keys are populated using spl_object_id
*
* $counter = new Counter();
* $a = new a();
* $b = new b();
*
* $counter->add($a);
* $counter->add($a);
* $counter->add($b);
* $counter->add($c);
* $counter->remove($b);
*
* $counter->count($a); // 2
* $counter->count($b); // 0
* $counter->count($c); // 1
*/
class Counter
{
protected array $objects;
protected array $objectsCounter;
/**
* Creates an instance of counter map
*/
public function __construct()
{
$this->objects = [];
$this->objectsCounter = [];
}
public function add($element)
{
$key = $this->getKey($element);
$this->objectsCounter[$key]++;
}
public function remove($element)
{
if (!$this->has($element)) {
throw new OutOfRangeException("\$element not found");
}
$key = $this->getKey($element);
$this->objectsCounter[$key]--;
}
public function count($element)
{
$key = $this->getKey($element);
return $this->objectsCounter[$key];
}
public function has($element)
{
return in_array($element, $this->objects);
}
protected function getKey($element)
{
if (!$this->has($element)) {
$key = $this->generateKey($element);
$this->objects[$key] = $element;
$this->objectsCounter[$key] = 0;
} else {
$key = array_search($element, $this->objects);
}
return $key;
}
protected function generateKey($element)
{
if (is_object($element)) {
return spl_object_id($element);
}
return $element;
}
}