aboutsummaryrefslogtreecommitdiff
path: root/src/content/usecases/HintKeyProducer.ts
blob: a5e2877593fa6caad9b4f5506d58d64f3f53f424 (plain) (blame)
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
export default class HintKeyProducer {
  private charset: string;

  private counter: number[];

  constructor(charset: string) {
    if (charset.length === 0) {
      throw new TypeError("charset is empty");
    }

    this.charset = charset;
    this.counter = [];
  }

  produce(): string {
    this.increment();

    return this.counter.map((x) => this.charset[x]).join("");
  }

  private increment(): void {
    const max = this.charset.length - 1;
    if (this.counter.every((x) => x === max)) {
      this.counter = new Array(this.counter.length + 1).fill(0);
      return;
    }

    this.counter.reverse();
    const len = this.charset.length;
    let num = this.counter.reduce((x, y, index) => x + y * len ** index) + 1;
    for (let i = 0; i < this.counter.length; ++i) {
      this.counter[i] = num % len;
      num = ~~(num / len);
    }
    this.counter.reverse();
  }
}