-
Notifications
You must be signed in to change notification settings - Fork 0
/
defaultKeyGenerator.ts
61 lines (48 loc) · 1.66 KB
/
defaultKeyGenerator.ts
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
import IKeyGenerator from "./IKeyGenerator";
const ALPHABET = "abcdefghijklmnopqrstuvwxyz";
const firstChar = ALPHABET.charAt(0);
const lastChar = ALPHABET.charAt(ALPHABET.length - 1);
function nextChar(char): string {
return char === lastChar
? firstChar
: ALPHABET.charAt(ALPHABET.indexOf(char) + 1);
}
export class DefaultKeyGenerator implements IKeyGenerator {
private _lastKey: string;
public setLastKey(key: string): IKeyGenerator {
this._lastKey = key;
return this;
}
public sortKeys(keyA: string, keyB: string): number {
return keyA.length > keyB.length ? 1 : keyA.length < keyB.length ? -1 : keyA > keyB ? 1 : 0;
}
public next(): string {
if (!this._lastKey) {
return this._lastKey = ALPHABET.charAt(0);
}
let parts = this._lastKey.split("");
const newParts = [];
let shouldAddChar = true;
let incrementNextChar = true;
for (let i = parts.length - 1; i >= 0; i--) {
if (parts[i] === lastChar) {
newParts.unshift(firstChar);
incrementNextChar = true;
} else if (incrementNextChar) {
newParts.unshift(nextChar(parts[i]));
shouldAddChar = false;
incrementNextChar = false;
} else {
shouldAddChar = false;
newParts.unshift(parts[i]);
}
}
if (shouldAddChar) {
newParts.push(firstChar);
}
return this._lastKey = newParts.join("");
}
}
export default function createDefaultKeyGenerator(): IKeyGenerator {
return new DefaultKeyGenerator();
}