1

I want to implement a password generator, but so that all options are written to a file (for example, from the numbers "0123456789" and the password length is 3) But the file write does not work for me and does not output only with a length of 3

function genPassword(){
    var possible = "0123456789".split(''),
    length = 3,
    i = 0,
    j = 0,
    step,
    comb;
    while(i<possible.length){
       step = possible[i];
       i++;
       while(j<possible.length){
        comb  = step + '' + possible.slice(j, j + (length -1)).join('');
        j++;
       return comb;
        
       }
       j=0;
       } 
   }  
 
const m = genPassword();
const fs = require("fs");
fs.writeFile('./text.json', JSON.stringify(m), (err) => {
    if (err) console.log(err);
});
Maks
  • 11
  • 1
  • `m` is not a JS data structure. Why stringify it? And your code does work but it outputs the same password every time. Are simply trying to pick 3 random numbers to form the password based on the length? – Andy Apr 04 '22 at 13:18
  • 001 012 023 034 045 056 067 078 089 09 101 112 123 134 145 156 167 178 189 19 201 212 223 234 245 – Maks Apr 04 '22 at 13:24
  • The result of the code – Maks Apr 04 '22 at 13:24
  • But these are not all options – Maks Apr 04 '22 at 13:24
  • Your code, as written in the question, will only produce `001`. Every time. – Andy Apr 04 '22 at 13:31
  • I forgot to replace here in the code return->console.log() – Maks Apr 04 '22 at 13:32
  • I can't find an error in the code why it doesn't display all possible length options – Maks Apr 04 '22 at 13:33
  • [Are you looking for all permutations of those numbers](https://stackoverflow.com/questions/9960908/permutations-in-javascript)? – Andy Apr 04 '22 at 13:34
  • "*But the file write does not work for me and does not output only with a length of 3*" - please be more specific about the problem. Does `m` have the correct, expected value, and only the file writing does not work? Or does `genPassword()` not return the expected value? Please narrow your question down to one of these and omit the irrelevant other. – Bergi Apr 04 '22 at 13:41
  • Although I find that it displays all possible variants of 3 digit numbers, I can't find an error here. – Maks Apr 04 '22 at 13:55

1 Answers1

0

If you want all possible passwords of a given length created from a given set of characters, you should loop through the array of characters each time picking one and then repeat that operation for each of the picked char till you have the requested number of characters for the password.

function genPassword() {
  var chars = "0123456789".split('');
  var passLen = 3;
  var stack = [""];
  var out = [];
  while (stack.length) {
    var curPass = stack.shift();
    var arr = curPass.length < passLen - 1 ? stack : out;
    for (let idx = 0; idx < chars.length; idx++) {
      arr.push(curPass + chars[idx]);
    }
  }
  return out;
}

console.log(genPassword());
marzelin
  • 10,790
  • 2
  • 30
  • 49