class Counter {
constructor() {
this.countsByKey = new Map();
}
getCountFor(key) {
const count = this.countsByKey.get(key);
return isFinite(count) ? count : 0;
}
incrementCountFor(key) {
this.countsByKey.set(key, this.getCountFor(key) + 1);
}
getKeysOrderedByDecreasingCount() {
return Array.from(this.countsByKey.keys()).sort((a, b) => {
return (
this.getCountFor(b) - this.getCountFor(a) ||
String(a).localeCompare(String(b))
);
});
}
}