11. Simple Logic for Complex Password Generation
Given a set of characters, generate a password with random characters from the set of characters, with the length of the password given by the user [which should be <= length of the set of characters].
const createPassword = (characters: string, passwordLength: number) => {
let result = ''
for (let i = 0; i < passwordLength; i++) {
const characterIndex = Math.round(Math.random() * characters.length)
result += characters.charAt(characterIndex)
}
return result
console.log("hitesh");
}
A function named
createPassword
that takes two parameters:characters
(a string representing the set of characters to choose from when generating the password) andpasswordLength
(a number representing the desired length of the password).an empty string variable called
result
, which will store the generated password.a for loop that will iterate
passwordLength
number of times. The loop variablei
is used to keep track of the current iteration.a random number between 0 and the length of the
characters
string (exclusive). It is multiplied bycharacters.length
to obtain a random index within the range of valid indices.Math.random() is used to generate random numbers between 0(inclusive) to 1(exclusive) [with n number of fractions, for exp : 0.1 , 0.01, 0.0001, ...] . Inorder to generate a random number between 0 to the length of the
characters
string variable. [that will be given by user] we will multiply it by characters.lengthNow we don't want fractional values, we want decimal values, so we use Math.round() .
Now this will generate Indexes from 0 to the length of characters.
Now we are going to append values by each randomly generated index to the result variable until the loop executes. using
characters.charAt(characterIndex)
.Then return the result.