@trackcity/collections
Version:
A Collection Util for trackcity cli
111 lines (100 loc) • 2.2 kB
JavaScript
class Collection {
constructor() {
this.map = new Map();
}
set(key, value) {
this.map.set(key, value);
}
contains(key) {
return this.map.has(key);
}
get(key) {
if (this.contains(key)) {
return this.map.get(key);
}
return undefined;
}
remove(key) {
let v = this.get(key);
this.map.delete(key);
return v;
}
getOrDefault(key, defaultValue) {
let v = this.get(key);
if (!v) v = defaultValue;
return v;
}
forEach(consumer) {
this.map.forEach((v, k, m) => {
consumer(k, v, this);
});
return this;
}
filter(consumer) {
let collection = new Collection();
this.forEach((k, v, c) => {
if (consumer(k, v, c)) {
collection.set(k, v);
}
});
return collection;
}
size() {
return this.map.size;
}
entries() {
let arr = [];
this.forEach((k, v, c) => {
arr.push([k, v]);
});
return arr;
}
keys() {
let arr = [];
this.forEach((k, v) => {
arr.push(k);
});
return arr;
}
values() {
let arr = [];
this.forEach((k, v) => {
arr.push(v);
});
return arr;
}
find(consumer) {
let v;
this.forEach((k, v, c) => {
if (consumer(k, v, c)) {
v = v;
return;
}
});
return v;
}
copy() {
let collection = new Collection();
if (this.isEmpty()) {
return collection;
}
this.forEach((k, v, c) => {
collection.set(k, v);
});
}
empty() {
if (this.isEmpty()) {
return this;
}
this.forEach((k, v, c) => {
this.remove(k);
});
return this;
}
isEmpty() {
return this.size() <= 0;
}
}
module.exports = {
Collection
}