UNPKG

1.89 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.NameGenerator = void 0;
7
8var _invariant = _interopRequireDefault(require("../invariant.js"));
9
10function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
12/**
13 * Copyright (c) 2017-present, Facebook, Inc.
14 * All rights reserved.
15 *
16 * This source code is licensed under the BSD-style license found in the
17 * LICENSE file in the root directory of this source tree. An additional grant
18 * of patent rights can be found in the PATENTS file in the same directory.
19 */
20function escapeInvalidIdentifierCharacters(s) {
21 let res = "";
22
23 for (let c of s) if (c >= "0" && c <= "9" || c >= "a" && c <= "z" || c >= "A" && c <= "Z") res += c;else res += "_" + c.charCodeAt(0);
24
25 return res;
26}
27
28const base62characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
29
30function base62encode(n) {
31 (0, _invariant.default)((n | 0) === n && n >= 0);
32 if (n === 0) return "0";
33 let s = "";
34
35 while (n > 0) {
36 let f = n % base62characters.length;
37 s = base62characters[f] + s;
38 n = (n - f) / base62characters.length;
39 }
40
41 return s;
42}
43
44class NameGenerator {
45 constructor(forbiddenNames, debugNames, uniqueSuffix, prefix) {
46 this.prefix = prefix;
47 this.uidCounter = 0;
48 this.debugNames = debugNames;
49 this.forbiddenNames = forbiddenNames;
50 this.uniqueSuffix = uniqueSuffix;
51 }
52
53 generate(debugSuffix) {
54 let id;
55
56 do {
57 id = this.prefix + base62encode(this.uidCounter++);
58 if (this.uniqueSuffix.length > 0) id += this.uniqueSuffix;
59
60 if (this.debugNames) {
61 if (debugSuffix) id += "_" + escapeInvalidIdentifierCharacters(debugSuffix);else id += "_";
62 }
63 } while (this.forbiddenNames.has(id));
64
65 return id;
66 }
67
68}
69
70exports.NameGenerator = NameGenerator;
71//# sourceMappingURL=NameGenerator.js.map
\No newline at end of file