UNPKG

stsys

Version:

String rewriting system (semi-Thue system)

116 lines (104 loc) 1.88 kB
class Bucket { constructor() { this.first = null; this.last = null; } getNext() { if (!this.first) return; const next = this.first; this.first = this.first.next; return next; } add(cp) { if (!this.first) this.first = this.last = cp; else { this.last.next = cp; this.last = cp; } } getSize() { let n = 0, cp = this.first; while (cp) { cp = cp.next; n++; } return n; } } class CpManager { constructor() { this.currentBucketIndex = -1; this.cpBuckets = []; } getNext() { if (!this.updateCurrentBucketIndex()) return; const bucket = this.cpBuckets[this.currentBucketIndex]; const cp = bucket.getNext(); if (!bucket.first) this.currentBucketIndex = -1; return cp; } hasNext() { return this.updateCurrentBucketIndex(); } updateCurrentBucketIndex() { if (this.currentBucketIndex >= 0) return true; for (let i in this.cpBuckets) { if (this.cpBuckets[i].first) { this.currentBucketIndex = i; return true; } } return false; } addCp(cp) { const w = cp.getWeight(); let bucket = this.cpBuckets[w]; if (this.currentBucketIndex < 0 || w < this.currentBucketIndex) this.currentBucketIndex = w; if (!bucket) bucket = this.cpBuckets[w] = new Bucket(); bucket.add(cp); } toString() { const sb = ['index: ' + this.currentBucketIndex]; for (let w in this.cpBuckets) { sb.push(w + ': ' + this.cpBuckets[w].getSize()); } return sb.join('\n'); } totalCpCount() { let count = 0; for (let w in this.cpBuckets) { count += this.cpBuckets[w].getSize(); } return count; } } module.exports.createCpManager = function() { return new CpManager(); };