aboutsummaryrefslogtreecommitdiff
path: root/src/content/domains/KeySequence.ts
blob: 4534b6091e0c67046829a9ba53d362de59c6b843 (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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import Key from '../../shared/settings/Key';

export default class KeySequence {
  constructor(
    public readonly keys: Key[],
  ) {
  }

  push(key: Key): number {
    return this.keys.push(key);
  }

  length(): number {
    return this.keys.length;
  }

  startsWith(o: KeySequence): boolean {
    if (this.keys.length < o.keys.length) {
      return false;
    }
    for (let i = 0; i < o.keys.length; ++i) {
      if (!this.keys[i].equals(o.keys[i])) {
        return false;
      }
    }
    return true;
  }

  isDigitOnly(): boolean {
    return this.keys.every(key => key.isDigit());
  }

  repeatCount(): number {
    let nonDigitAt = this.keys.findIndex(key => !key.isDigit());
    if (this.keys.length === 0 || nonDigitAt === 0) {
      return 1;
    }
    if (nonDigitAt === -1) {
      nonDigitAt = this.keys.length;
    }
    let digits = this.keys.slice(0, nonDigitAt)
      .map(key => key.key)
      .join('');
    return Number(digits);
  }

  trimNumericPrefix(): KeySequence {
    let nonDigitAt = this.keys.findIndex(key => !key.isDigit());
    if (nonDigitAt === -1) {
      nonDigitAt = this.keys.length;
    }
    return new KeySequence(this.keys.slice(nonDigitAt));
  }

  splitNumericPrefix(): [KeySequence, KeySequence] {
    let nonDigitIndex = this.keys.findIndex(key => !key.isDigit());
    if (nonDigitIndex === -1) {
      return [this, new KeySequence([])];
    }
    return [
      new KeySequence(this.keys.slice(0, nonDigitIndex)),
      new KeySequence(this.keys.slice(nonDigitIndex)),
    ];
  }

  static fromMapKeys(keys: string): KeySequence {
    const fromMapKeysRecursive = (
      remaining: string, mappedKeys: Key[],
    ): Key[] => {
      if (remaining.length === 0) {
        return mappedKeys;
      }

      let nextPos = 1;
      if (remaining.startsWith('<')) {
        let ltPos = remaining.indexOf('>');
        if (ltPos > 0) {
          nextPos = ltPos + 1;
        }
      }

      return fromMapKeysRecursive(
        remaining.slice(nextPos),
        mappedKeys.concat([Key.fromMapKey(remaining.slice(0, nextPos))])
      );
    };

    let data = fromMapKeysRecursive(keys, []);
    return new KeySequence(data);
  }
}