NameManager.js 642 B

123456789101112131415161718192021222324252627
  1. import getIdentifierNames from "./util/getIdentifierNames";
  2. export default class NameManager {
  3. __init() {this.usedNames = new Set()}
  4. constructor(code, tokens) {;NameManager.prototype.__init.call(this);
  5. this.usedNames = new Set(getIdentifierNames(code, tokens));
  6. }
  7. claimFreeName(name) {
  8. const newName = this.findFreeName(name);
  9. this.usedNames.add(newName);
  10. return newName;
  11. }
  12. findFreeName(name) {
  13. if (!this.usedNames.has(name)) {
  14. return name;
  15. }
  16. let suffixNum = 2;
  17. while (this.usedNames.has(name + String(suffixNum))) {
  18. suffixNum++;
  19. }
  20. return name + String(suffixNum);
  21. }
  22. }