All files / player-engine/src/course/nonstop ids.ts

100% Statements 21/21
100% Branches 7/7
100% Functions 3/3
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42261x     261x                 1426x     1426x 1426x       58476x 58476x 58476x 45915x 45829x 45829x 45829x 95423x 95423x   45829x 45829x 45829x 45829x         50x      
const BASE62_DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
 
/** Base-62 object keys a stitched chart can name (`01`-`zz`), the most a two-character key reaches. */
export const NONSTOP_KEY_SPACE: number = 62 * 62 - 1;
 
/**
 * Hands out two-character base-62 object keys (`01`, `02`, … `zz`) for one resource table of a stitched chart, one per
 * distinct source key of each stage. Returns `undefined` once the key space is used up.
 */
export class NonstopKeyAllocator {
  private readonly unlimited: boolean;
  constructor(unlimited = false) {
    this.unlimited = unlimited;
  }
 
  private next = 1;
  private readonly keys = new Map<string, string>();
 
  /** The stitched key for `sourceKey` of `stage`, allocating it on first use. */
  keyFor(stage: number, sourceKey: string): string | undefined {
    const id = `${stage}:${sourceKey}`;
    const known = this.keys.get(id);
    if (known !== undefined) return known;
    if (!this.unlimited && this.next > NONSTOP_KEY_SPACE) return undefined;
    let value = this.next;
    let key = '';
    do {
      key = BASE62_DIGITS[value % 62]! + key;
      value = Math.floor(value / 62);
    } while (value > 0);
    key = key.padStart(2, '0');
    this.next += 1;
    this.keys.set(id, key);
    return key;
  }
 
  /** A fresh key not tied to a source key (stitched STOP lengths). */
  fresh(): string | undefined {
    return this.keyFor(-1, String(this.next));
  }
}