@typecad/typecad
Version:
🤖programmatically 💥create 🛰️hardware
31 lines (30 loc) • 988 B
JavaScript
export class ReferenceCounter {
constructor() {
this.counters = new Map();
this.usedReferences = new Set();
}
getNextReference(prefix) {
let nextRef;
let currentCount = this.counters.get(prefix) || 0;
do {
currentCount++;
nextRef = `${prefix}${currentCount}`;
} while (this.usedReferences.has(nextRef));
this.counters.set(prefix, currentCount);
this.usedReferences.add(nextRef);
return nextRef;
}
setReference(reference) {
if (this.usedReferences.has(reference)) {
return false;
}
const prefix = reference.match(/^[#]?[a-zA-Z]+/)[0].toLowerCase();
const number = parseInt(reference.match(/\d+/)[0]);
this.usedReferences.add(reference);
const currentCount = this.counters.get(prefix) || 0;
if (number > currentCount) {
this.counters.set(prefix, number);
}
return true;
}
}