Created
May 20, 2020 11:19
-
-
Save furqanbaqai/9c796f71c00d3c8184fb59ebde6359ec to your computer and use it in GitHub Desktop.
Generating alpha numeric characters in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Manage robot factory settings. | |
* | |
* When robots come off the factory floor, they have no name. | |
* | |
* The first time you boot them up, a random name is generated in the format | |
* of two uppercase letters followed by three digits, such as RX837 or BC811. | |
* | |
* Every once in a while we need to reset a robot to its factory settings, | |
* which means that their name gets wiped. The next time you ask, it will | |
* respond with a new random name. | |
* | |
* The names must be random: they should not follow a predictable sequence. | |
* Random names means a risk of collisions. Your solution must ensure that | |
* every existing robot has a unique name. | |
* | |
*/ | |
class RobotName { | |
private _name = ''; | |
private readonly _characters: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
public static _GENERTED_NAMES = new Set(); | |
private readonly _MAX_YIELDS = 3; | |
constructor() { | |
this.generateName(); | |
} | |
private generateName(): void{ | |
let rand: number = Math.random(); | |
let tempName: string = ""; | |
for(let i=0; i<this._MAX_YIELDS ; i++){ | |
rand = Math.floor((rand *1000 < 100)? rand * 10000:rand * 1000); | |
tempName = this.getRandomChar(2) + rand | |
if(!RobotName._GENERTED_NAMES.has(tempName)){ | |
RobotName._GENERTED_NAMES.add(tempName); | |
break; // break the loop here | |
} | |
} | |
this._name = tempName; | |
} | |
private getRandomChar(length: number): string{ | |
let output = ""; | |
for(let i = 0; i<length; i++){ | |
output += this._characters.charAt(Math.floor(Math.random() * 26)); | |
} | |
return output; | |
} | |
get name(): string{ | |
return this._name; | |
} | |
public resetName(): void{ | |
this.generateName(); | |
} | |
} | |
export default RobotName; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment