forked from josdejong/mathjs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlruQueue.js
More file actions
50 lines (50 loc) · 1.17 KB
/
lruQueue.js
File metadata and controls
50 lines (50 loc) · 1.17 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
// (c) 2018, Mariusz Nowak
// SPDX-License-Identifier: ISC
// Derived from https://github.com/medikoo/lru-queue
export function lruQueue (limit) {
let size = 0
let base = 1
let queue = Object.create(null)
let map = Object.create(null)
let index = 0
const del = function (id) {
const oldIndex = map[id]
if (!oldIndex) return
delete queue[oldIndex]
delete map[id]
--size
if (base !== oldIndex) return
if (!size) {
index = 0
base = 1
return
}
while (!hasOwnProperty.call(queue, ++base)) continue
}
limit = Math.abs(limit)
return {
hit: function (id) {
const oldIndex = map[id]; const nuIndex = ++index
queue[nuIndex] = id
map[id] = nuIndex
if (!oldIndex) {
++size
if (size <= limit) return undefined
id = queue[base]
del(id)
return id
}
delete queue[oldIndex]
if (base !== oldIndex) return undefined
while (!hasOwnProperty.call(queue, ++base)) continue
return undefined
},
delete: del,
clear: function () {
size = index = 0
base = 1
queue = Object.create(null)
map = Object.create(null)
}
}
};