The North Pole has security concerns. First Santa Claus loses the message code). Then the elf in charge of the keys always uses the same one. Time to change all the locks. But this time, instead of keys, we will use passwords. Of different length and difficulty depending on the level of safety.

The puzzle: Keeping Secrets Safe 🔑

Day 11 of the Dev Advent Calendar 🎅: Today’s problem is about creating passwords. We need to generate different passwords using different character sets.

The starting function is like this:

length is a number: it is the length of the password. options instead is an object containing 4 properties:

To simplify, problem tests always consider every property in the options object to be true. Likewise, it is not necessary to pass all properties to the function.

The generatePassword function returns a string of random characters. There must be a character for each option property.

I start with catch mistakes. I need to verify that the options argument is not empty. To do this I use the Object.keys() method. This method returns an array with the names of the various properties of an object. Just check its length to understand if there are properties or not:

I use the same variable to verify that the required length is correct:

The next step is to make sure there is at least one character of each type selected. To do this I had to decide how the password will be generated. I think a good method would be to create each character independently and save it into an array. Then I’ll mix the array with all the characters and turn it into a string with the Array.prototype.join() method.

To manage the character sets, however, I use a separate object. In this way I can, in the future, increase or decrease the available properties:

I create a helper function to pick a random letter from a string.

It remains to understand how to scroll through the various properties of an object. I need to decide which character sets to use. To do this I use the for…in statement. By combining these three pieces I can be sure that I have a character for each set selected in the password:

For the remaining characters I reuse the randomChar() function. But passing all available characters as an argument. So I add a characters variable and start typing random letters in the password:

Finally I create a helper function to mix the array:

This is my solution to the puzzle:

That’s all for today. To help me keep track of this series of posts I’ve created a list on Medium: Dev Advent Calendar - The advent diary of an amateur programmer.