Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active March 13, 2025 22:13
Show Gist options
  • Save primaryobjects/833ad367f1055ffd261c4bb880444e94 to your computer and use it in GitHub Desktop.
Save primaryobjects/833ad367f1055ffd261c4bb880444e94 to your computer and use it in GitHub Desktop.
Create a class with add, remove, random - technical interview example question https://jsfiddle.net/1jhfvpz5/1/
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}`);
});
1,2,3,4,5,6,7,8,9
1,2,3,4,9,6,7,8
1: 12.45
2: 12.46
3: 12.17
4: 12.839999999999998
6: 12.32
7: 12.8
8: 12.55
9: 12.41
6,2,7,4,9
2: 19.59
4: 20.01
6: 19.85
7: 20.169999999999998
9: 20.380000000000003
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment