HexadecimalIdentifierNamesGenerator.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 { AbstractIdentifierNamesGenerator } from './AbstractIdentifierNamesGenerator';
  6. import { Utils } from '../../utils/Utils';
  7. @injectable()
  8. export class HexadecimalIdentifierNamesGenerator extends AbstractIdentifierNamesGenerator {
  9. /**
  10. * @type {number}
  11. */
  12. private static readonly baseIdentifierNameLength: number = 6;
  13. /**
  14. * @type {Set<string>}
  15. */
  16. private readonly randomVariableNameSet: Set <string> = new Set();
  17. /**
  18. * @param {IRandomGenerator} randomGenerator
  19. * @param {IOptions} options
  20. */
  21. constructor (
  22. @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
  23. @inject(ServiceIdentifiers.IOptions) options: IOptions
  24. ) {
  25. super(randomGenerator, options);
  26. }
  27. /**
  28. * @returns {string}
  29. */
  30. public generate (): string {
  31. const rangeMinInteger: number = 10000;
  32. const rangeMaxInteger: number = 99999999;
  33. const randomInteger: number = this.randomGenerator.getRandomInteger(rangeMinInteger, rangeMaxInteger);
  34. const hexadecimalNumber: string = Utils.decToHex(randomInteger);
  35. const baseIdentifierName: string = hexadecimalNumber.substr(0, HexadecimalIdentifierNamesGenerator.baseIdentifierNameLength);
  36. const identifierName: string = `_${Utils.hexadecimalPrefix}${baseIdentifierName}`;
  37. if (this.randomVariableNameSet.has(identifierName)) {
  38. return this.generate();
  39. }
  40. this.randomVariableNameSet.add(identifierName);
  41. return identifierName;
  42. }
  43. /**
  44. * @returns {string}
  45. */
  46. public generateWithPrefix (): string {
  47. const identifierName: string = this.generate();
  48. return `${this.options.identifiersPrefix}${identifierName}`.replace('__', '_');
  49. }
  50. }