HexadecimalIdentifierNameGenerator.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { inject, injectable } from 'inversify';
  2. import { ServiceIdentifiers } from '../../container/ServiceIdentifiers';
  3. import { IOptions } from '../../interfaces/options/IOptions';
  4. import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
  5. import { AbstractIdentifierNameGenerator } from './AbstractIdentifierNameGenerator';
  6. import { Utils } from '../../utils/Utils';
  7. @injectable()
  8. export class HexadecimalIdentifierNameGenerator extends AbstractIdentifierNameGenerator {
  9. /**
  10. * @type {Set<string>}
  11. */
  12. private readonly randomVariableNameSet: Set <string> = new Set();
  13. /**
  14. * @param {IRandomGenerator} randomGenerator
  15. * @param {IOptions} options
  16. */
  17. constructor (
  18. @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
  19. @inject(ServiceIdentifiers.IOptions) options: IOptions
  20. ) {
  21. super(randomGenerator, options);
  22. }
  23. /**
  24. * @param {number} length
  25. * @returns {string}
  26. */
  27. public generate (length: number): string {
  28. const prefix: string = `_${Utils.hexadecimalPrefix}`;
  29. const rangeMinInteger: number = 10000;
  30. const rangeMaxInteger: number = 99999999;
  31. const randomInteger: number = this.randomGenerator.getRandomInteger(rangeMinInteger, rangeMaxInteger);
  32. const hexadecimalNumber: string = Utils.decToHex(randomInteger);
  33. const randomVariableName: string = `${prefix}${hexadecimalNumber.substr(0, length)}`;
  34. if (this.randomVariableNameSet.has(randomVariableName)) {
  35. return this.generate(length);
  36. }
  37. this.randomVariableNameSet.add(randomVariableName);
  38. return randomVariableName;
  39. }
  40. }