| 1 |
'use strict'; |
| 2 |
|
| 3 |
var toPosInt = require('es5-ext/number/to-pos-integer') |
| 4 |
|
| 5 |
, create = Object.create, hasOwnProperty = Object.prototype.hasOwnProperty; |
| 6 |
|
| 7 |
module.exports = function (limit) { |
| 8 |
var size = 0, base = 1, queue = create(null), map = create(null), index = 0, del; |
| 9 |
limit = toPosInt(limit); |
| 10 |
return { |
| 11 |
hit: function (id) { |
| 12 |
var oldIndex = map[id], nuIndex = ++index; |
| 13 |
queue[nuIndex] = id; |
| 14 |
map[id] = nuIndex; |
| 15 |
if (!oldIndex) { |
| 16 |
++size; |
| 17 |
if (size <= limit) return; |
| 18 |
id = queue[base]; |
| 19 |
del(id); |
| 20 |
return id; |
| 21 |
} |
| 22 |
delete queue[oldIndex]; |
| 23 |
if (base !== oldIndex) return; |
| 24 |
while (!hasOwnProperty.call(queue, ++base)) continue; //jslint: skip |
| 25 |
}, |
| 26 |
delete: del = function (id) { |
| 27 |
var oldIndex = map[id]; |
| 28 |
if (!oldIndex) return; |
| 29 |
delete queue[oldIndex]; |
| 30 |
delete map[id]; |
| 31 |
--size; |
| 32 |
if (base !== oldIndex) return; |
| 33 |
if (!size) { |
| 34 |
index = 0; |
| 35 |
base = 1; |
| 36 |
return; |
| 37 |
} |
| 38 |
while (!hasOwnProperty.call(queue, ++base)) continue; //jslint: skip |
| 39 |
}, |
| 40 |
clear: function () { |
| 41 |
size = 0; |
| 42 |
base = 1; |
| 43 |
queue = create(null); |
| 44 |
map = create(null); |
| 45 |
index = 0; |
| 46 |
} |
| 47 |
}; |
| 48 |
}; |