• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import type {INameGenerator, NameGeneratorOptions} from './INameGenerator';
17import {ListUtil} from '../utils/ListUtil';
18
19/**
20 * @Desc: simple disordered name generator
21 * e.g.: c, b, z, a, ..., d1, a1, z1, ...
22 */
23export class DisorderNameGenerator implements INameGenerator {
24  private mCharIndex: number;
25  private mLoopNumber: number;
26  private mReservedNames: Set<string>;
27
28  private readonly CHAR_COUNT: number = 26;
29  private readonly CHAR_CODE_A: number = 97;
30
31  private readonly mCharIndexList: number[];
32
33  constructor(options?: NameGeneratorOptions) {
34    this.mCharIndex = 0;
35    this.mLoopNumber = 0;
36    this.mReservedNames = options?.reservedNames;
37
38    this.mCharIndexList = ListUtil.getInitList(this.CHAR_COUNT);
39    ListUtil.shuffle(this.mCharIndexList);
40  }
41
42  private updateElements(): void {
43    this.mCharIndex = (this.mCharIndex + 1) % this.CHAR_COUNT;
44
45    if (this.mCharIndex === 0) {
46      this.mLoopNumber += 1;
47      ListUtil.shuffle(this.mCharIndexList);
48    }
49  }
50
51  public getName(): string {
52    let generatedName: string = String.fromCharCode(this.CHAR_CODE_A + this.mCharIndexList[this.mCharIndex]);
53    if (this.mLoopNumber > 0) {
54      generatedName += this.mLoopNumber;
55    }
56
57    // update elements after generate name
58    this.updateElements();
59    if (this.mReservedNames?.has(generatedName)) {
60      return this.getName();
61    }
62
63    return generatedName;
64  }
65
66  public reset(): void {
67    this.mCharIndex = 0;
68    this.mLoopNumber = 0;
69    ListUtil.shuffle(this.mCharIndexList);
70  }
71}
72