stylus/js/cache.js

72 lines
1.4 KiB
JavaScript
Raw Normal View History

2018-10-10 16:54:38 +00:00
/* exported createCache */
2018-10-04 04:46:19 +00:00
'use strict';
2018-10-10 16:54:38 +00:00
// create a FIFO limit-size map.
2018-10-13 07:58:31 +00:00
function createCache({size = 1000, onDeleted} = {}) {
2018-10-04 04:46:19 +00:00
const map = new Map();
2018-10-03 19:35:07 +00:00
const buffer = Array(size);
let index = 0;
let lastIndex = 0;
return {
get,
set,
delete: delete_,
clear,
has: id => map.has(id),
2018-10-10 08:14:51 +00:00
entries: function *() {
for (const [id, item] of map) {
yield [id, item.data];
}
},
values: function *() {
for (const item of map.values()) {
yield item.data;
}
},
2018-10-04 04:46:19 +00:00
get size() {
return map.size;
}
2018-10-03 19:35:07 +00:00
};
function get(id) {
const item = map.get(id);
return item && item.data;
}
function set(id, data) {
if (map.size === size) {
// full
map.delete(buffer[lastIndex].id);
2018-10-13 07:58:31 +00:00
if (onDeleted) {
onDeleted(buffer[lastIndex].id, buffer[lastIndex].data);
}
2018-10-03 19:35:07 +00:00
lastIndex = (lastIndex + 1) % size;
}
const item = {id, data, index};
map.set(id, item);
buffer[index] = item;
index = (index + 1) % size;
}
function delete_(id) {
const item = map.get(id);
if (!item) {
2018-10-13 07:58:31 +00:00
return false;
2018-10-03 19:35:07 +00:00
}
map.delete(item.id);
const lastItem = buffer[lastIndex];
lastItem.index = item.index;
buffer[item.index] = lastItem;
lastIndex = (lastIndex + 1) % size;
2018-10-13 07:58:31 +00:00
if (onDeleted) {
onDeleted(item.id, item.data);
}
return true;
2018-10-03 19:35:07 +00:00
}
function clear() {
map.clear();
index = lastIndex = 0;
}
}