# randomPassword()

💾 [replit](https://replit.com/@pegasusroe/random-password#index.js)

{% tabs %}
{% tab title="randomPassword( )" %}

```javascript
// ⭐️ 預設密碼長度：32
function randomPassword(length = 32, {
    digit      = true,      // 要有數字
    lowercase  = true,      // 要有小寫
    uppercase  = true,      // 要有大寫
    underscore = true,      // 可以有 "_"
    symbol     = true,      // 特殊符號
}={}){

    // 1. 字集
    let digits   = String.fromCharCodesBetween(48, 57);    // '0...9'
    let letters  = String.fromCharCodesBetween(97, 122);  // 'a...z'
    let capitals = String.fromCharCodesBetween(65, 90);   // 'A...Z'
    let symbols  = "!@#$%^&*";
    let underscores = "_";

    // 2. 準備組合密碼
    let pwd = '';                       // 密碼
    let candidates = '';                // 密碼候選字

    // 3. 從必用的字集中選字
    [
        [digit, digits],                // 數字
        [lowercase, letters],           // 小寫
        [uppercase, capitals],          // 大寫
        [underscore, underscores],      // 底線 "_"
        [symbol, symbols],              // 特殊符號

    ].forEach(([include, chars]) => {
        if(include){                    // 如果要加入 
            pwd += chars.random();      // 先加入一個字元
            candidates += chars;        // 整組字集加入候選字
        }
    });

    // 4. 如果密碼長度不足，就繼續選字
    let k = pwd.length;                 // 目前密碼長度
    let n = candidates.length;          // 選用字總長度

    while(k < length){
        pwd += candidates.random();
        k += 1;
    }

    return pwd.shuffle();
}
```

{% endtab %}

{% tab title="helpers" %}

```javascript
const { log } = console;
const { floor, random: rand } = Math;

/* --------------- helpers --------------- */

// ⭐️ random int: 0 ... n-1
//    randomInt(5): choose from 0, 1, 2, 3, 4
function randomInt(n){
    return floor( n * rand() );
}

// ⭐️ array.random()
Array.prototype.random = function(){
    return this[randomInt(this.length)];
};

// ⭐️ string.random()
// ⭐️ Note: this may not work well with Unicode❗️ 
String.prototype.random = function(){
    return this[randomInt(this.length)];
}

// ⭐️ string.shuffle()
String.prototype.shuffle = function(){

    var a = this.split("");
    var n = a.length;

    for(var i = n - 1; i > 0; i--) {
        var j = randomInt(i+1);
        [a[i], a[j]] = [a[j], a[i]];
    }

    return a.join("");
}

// ⭐️ String.fromCharCodesBetween(65, 70) -> 'ABCDEF'
String.fromCharCodesBetween = function(from, to){
    let array = [];
    for(let i = from; i <= to; i++) array.push(i);
    return array
        .map(code => String.fromCharCode(code))
        .join('');
};
```

{% endtab %}

{% tab title="📗 參考" %}

* [Array 常用函數](/web/js/val/builtin/arr.md)
  {% endtab %}

{% tab title="⬆️ 相依" %}

* [String.fromCharCodesBetween(from, to)](/web/js/val/prim/str/method/string.fromcharcodesbetween.md)
* [randomInt()](/web/js/val/prim/num/random/randomint.md)
* [array.random()](/web/js/val/builtin/arr/ext/random.md)
* [string.random()](/web/js/val/prim/str/method/.random.md)
* [string.shuffle()](/web/js/val/prim/str/method/string.shuffle.md)
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/web/appendix/custom/custom-functions/random-password.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
