unique-list
Version:
A mix of an Array an a Map.
74 lines (73 loc) • 1.9 kB
JavaScript
"use strict";
class UniqueList {
constructor(uniqueCallBack, initialValues) {
this.uniqueCallBack = uniqueCallBack;
this.hash = {};
this.list = new Array();
if (initialValues) {
this.pushAll(initialValues);
}
}
hasItem(id) {
return this.hash[id] !== undefined;
}
get(id) {
return this.hash[id];
}
getAllKeys() {
var keys = new Array();
for (var prop in this.hash) {
keys.push(prop);
}
return keys;
}
getAll() {
return this.list;
}
getAt(idx) {
return this.list[idx];
}
setAt(idx, item) {
this.list[idx] = item;
this.hash[this.uniqueCallBack(item)] = item;
}
hasItems() {
return this.list.length > 0;
}
push(item) {
var uniqueId = this.uniqueCallBack(item);
if (!this.hash[uniqueId]) {
this.hash[uniqueId] = item;
this.list.push(item);
this.length = this.list.length;
}
}
pushAll(items) {
items.forEach(value => {
this.push(value);
});
}
insertAt(item, idx) {
var uniqueId = this.uniqueCallBack(item);
if (!this.hash[uniqueId]) {
this.hash[uniqueId] = item;
this.list.splice(idx, 0, item);
this.length = this.list.length;
}
}
remove(item) {
var uniqueId = this.uniqueCallBack(item);
if (this.hash[uniqueId]) {
var idx = this.list.indexOf(item);
this.list.splice(idx, 1);
this.length = this.list.length;
delete this.hash[uniqueId];
}
}
clear() {
this.list = [];
this.hash = {};
this.length = 0;
}
}
exports.UniqueList = UniqueList;