JSFiddle - React, Tailwind, and code Playground
JavaScript
class Store {
values = [];
indices = {};
constructor() {
this.values = [];
this.indices = {};
}
add(value) {
let index;
if (typeof(value) === 'object') {
this.addRange(value);
}
else {
if (!this.indices[value]) {
this.values.push(value);
index = this.values.length - 1;
this.indices[value] = index;
}
}
return index;
}
addRange(values) {
values.forEach(value => {
this.add(value);
});
}
remove(value) {
const index = this.indices[value];
if (index !== undefined) {
const swapValue = this.values.pop();
this.values[index] = swapValue;
this.indices[swapValue] = index;
delete this.indices[value];
}
return index;
}
random() {
const index = Math.floor(Math.random() * this.values.length);
return this.values[index];
}
toString() {
return this.values.toString();
}
}
const store = new Store();
store.add(1);
store.add([2, 3, 4, 5, 6, 7, 8, 9])
console.log(store.toString());
store.remove(5);
console.log(store.toString());
let counts = {};
const total = 10000;
for (let i=0; i<total; i++) {
const value = store.random();
counts[value] = counts[value] ? counts[value] + 1 : 1;
}
Object.keys(counts).forEach(value => {
const count = counts[value];
console.log(`${value}: ${count / total * 100}`);
});
store.remove(1);
store.remove(3);
store.remove(8);
console.log(store.toString());
counts = {};
for (let i=0; i<total; i++) {
const value = store.random();
counts[value] = counts[value] ? counts[value] + 1 : 1;
}
Object.keys(counts).forEach(value => {
const count = counts[value];
console.log(`${value}: ${count / total * 100}`);
});