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'; 17 18/** 19 * @desc simple ordered name generator, e.g.: a, b, c, d, ..., a1, b1, c1, ... 20 */ 21export class OrderedNameGenerator implements INameGenerator { 22 private mCharIndex: number; 23 private mLoopNumber: number; 24 private mReservedNames: Set<string>; 25 26 private readonly CHAR_COUNT: number = 26; 27 private readonly CHAR_CODE_A: number = 97; 28 29 constructor(options?: NameGeneratorOptions) { 30 this.mCharIndex = 0; 31 this.mLoopNumber = 0; 32 this.mReservedNames = options?.reservedNames; 33 } 34 35 private updateElements(): void { 36 this.mCharIndex = (this.mCharIndex + 1) % this.CHAR_COUNT; 37 if (this.mCharIndex === 0) { 38 this.mLoopNumber += 1; 39 } 40 } 41 42 public getName(): string { 43 let generatedName: string = String.fromCharCode(this.CHAR_CODE_A + this.mCharIndex); 44 if (this.mLoopNumber > 0) { 45 generatedName += this.mLoopNumber; 46 } 47 48 this.updateElements(); 49 if (this.mReservedNames?.has(generatedName)) { 50 return this.getName(); 51 } 52 53 return generatedName; 54 } 55 56 public reset(): void { 57 this.mCharIndex = 0; 58 this.mLoopNumber = 0; 59 } 60} 61