-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRUCache.php
49 lines (40 loc) · 1.07 KB
/
LRUCache.php
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
<?php
class LRUCache {
const DEFAULT_LIMIT = 2;
private $list = array();
// 限界保持数
private $limit;
function __construct ( $limit = self::DEFAULT_LIMIT ){
$this->changeLimit($limit);
}
function changeLimit($limit = self::DEFAULT_LIMIT) {
$this->limit = $limit;
$tmp = $this->list;
foreach($tmp as $key => $val) {
$this->put($key, $val);
}
}
function put( $key, $value ){
unset($this->list[$key]);
$this->list[$key] = $value;
// if( count($this->list) > $this->limit ){
while( count($this->list) > $this->limit ) {
unset( $this->list[$this->getOldest()]);
}
}
function get( $key ){
if (!array_key_exists($key, $this->list)) {
return null;
}
$value = $this->list[$key];
$this->put($key, $value);
return $value;
}
function getOldest() {
// reset($this->list);
return key($this->list);
}
function getLimit() {
return $this->limit;
}
}