mirror of
https://github.com/discordjs/discord.js.git
synced 2026-05-30 23:50:07 +00:00
111 lines
2.3 KiB
JavaScript
111 lines
2.3 KiB
JavaScript
"use strict";
|
|
|
|
var discrimS = Symbol();
|
|
var discrimCacheS = Symbol();
|
|
|
|
export default class Cache extends Array {
|
|
constructor(discrim, limit) {
|
|
super();
|
|
this[discrimS] = discrim || "id";
|
|
this[discrimCacheS] = {};
|
|
this.limit = limit;
|
|
}
|
|
|
|
get(key, value) {
|
|
if (typeof key === 'function') {
|
|
var valid = key;
|
|
key = null;
|
|
} else if (key === this[discrimS] && typeof value === "string") {
|
|
return this[discrimCacheS][value] || null;
|
|
} else if (value && value.constructor.name === 'RegExp') {
|
|
var valid = function valid(item) {
|
|
return value.test(item);
|
|
}
|
|
} else if (typeof value !== 'function') {
|
|
var valid = function valid(item) {
|
|
return item == value;
|
|
}
|
|
}
|
|
|
|
for (var item of this) {
|
|
if (valid(key == null ? item : item[key])) {
|
|
return item;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
has(object) {
|
|
return !!this.get(this[discrimS], object[this[discrimS]]);
|
|
}
|
|
|
|
getAll(key, value) {
|
|
var found = new Cache(this[discrimS]);
|
|
|
|
if (typeof key === 'function') {
|
|
var valid = key;
|
|
key = null;
|
|
} else if (value && value.constructor.name === 'RegExp') {
|
|
var valid = function valid(item) {
|
|
return value.test(item);
|
|
}
|
|
} else if (typeof value !== 'function') {
|
|
var valid = function valid(item) {
|
|
return item == value;
|
|
}
|
|
}
|
|
|
|
for (var item of this) {
|
|
if (valid(key == null ? item : item[key])) {
|
|
found.add(item);
|
|
}
|
|
}
|
|
|
|
return found;
|
|
}
|
|
|
|
add(data) {
|
|
var cacheKey = data[this[discrimS]];
|
|
if (this[discrimCacheS][cacheKey]) {
|
|
return this[discrimCacheS][cacheKey];
|
|
}
|
|
if (this.limit && this.length >= this.limit) {
|
|
this.splice(0, 1);
|
|
}
|
|
this.push(data);
|
|
this[discrimCacheS][cacheKey] = data;
|
|
return data;
|
|
}
|
|
|
|
update(old, data) {
|
|
for(var i in this) {
|
|
if(this[i][this[discrimS]] === old[this[discrimS]]) {
|
|
for (var key in data) {
|
|
if (data.hasOwnProperty(key)) {
|
|
this[i][key] = data[key];
|
|
}
|
|
}
|
|
this[discrimCacheS][data[this[discrimS]]] = this[i];
|
|
return this[i];
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
random() {
|
|
return this[Math.floor(Math.random()*this.length)];
|
|
}
|
|
|
|
remove(data) {
|
|
delete this[discrimCacheS][data[this[discrimS]]];
|
|
for(var i in this) {
|
|
if(this[i][this[discrimS]] === old[this[discrimS]]) {
|
|
this.splice(i, 1);
|
|
return this[i];
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
}
|