| 1 | 1 | // This is only a SKELETON file for the 'Robot Name' exercise. It's been |
| 2 | 2 | // provided as a convenience to get your started writing code faster. |
| 3 | 3 | |
| 4 | const usedNames = new Set(); | |
| 5 | ||
| 4 | 6 | export class Robot { |
| 7 | constructor() { | |
| 8 | this._name = this.generateName(); | |
| 9 | } | |
| 10 | ||
| 5 | 11 | /** |
| 6 | 12 | * @return {string} |
| 7 | 13 | */ |
| 13 | 19 | * @return {void} |
| 14 | 20 | */ |
| 15 | 21 | reset() { |
| 16 | throw new Error('Remove this line and implement the function'); | |
| 22 | // Edge Case: Remove old name from used names set before generating new one | |
| 23 | if (this._name) { | |
| 24 | usedNames.delete(this._name); | |
| 25 | } | |
| 26 | this._name = this.generateName(); | |
| 27 | } | |
| 28 | ||
| 29 | generateName() { | |
| 30 | // Edge Case: Handle maximum possible name exhaustion | |
| 31 | if (usedNames.size >= 26 * 26 * 10 * 10 * 10) { | |
| 32 | throw new Error("All possible names have been used"); | |
| 33 | } | |
| 34 | ||
| 35 | let newName; | |
| 36 | do { | |
| 37 | const letters = String.fromCharCode( | |
| 38 | Math.floor(Math.random() * 26) + 65, | |
| 39 | Math.floor(Math.random() * 26) + 65 | |
| 40 | ); | |
| 41 | const numbers = Math.floor(Math.random() * 1000) | |
| 42 | .toString() | |
| 43 | .padStart(3, '0'); | |
| 44 | newName = letters + numbers; | |
| 45 | } while (usedNames.has(newName)); | |
| 46 | ||
| 47 | usedNames.add(newName); | |
| 48 | return newName; | |
| 17 | 49 | } |
| 18 | 50 | } |
| 19 | 51 | |
| 20 | 52 | /** |
| 21 | 53 | * @return {void} |
| 22 | 54 | */ |
| 23 | Robot.releaseNames = () => {}; | |
| 55 | Robot.releaseNames = () => { | |
| 56 | // Edge Case: Clear all used names to allow reuse | |
| 57 | usedNames.clear(); | |
| 58 | }; | |
| 59 | ||
| 60 | // Handled Edge Cases: name collision handling, maximum possible name exhaustion, persistence of generated names |