idchunk 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/index.js +32 -15
package/package.json
CHANGED
package/src/index.js
CHANGED
|
@@ -1,26 +1,43 @@
|
|
|
1
|
-
|
|
1
|
+
let nodeCrypto;
|
|
2
|
+
try {
|
|
3
|
+
nodeCrypto = require("crypto");
|
|
4
|
+
} catch {
|
|
5
|
+
nodeCrypto = null;
|
|
6
|
+
}
|
|
2
7
|
|
|
3
|
-
const DEFAULT_VALUES =
|
|
8
|
+
const DEFAULT_VALUES =
|
|
9
|
+
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
|
|
4
10
|
|
|
5
11
|
function getRandomInt(max) {
|
|
6
|
-
|
|
7
|
-
|
|
12
|
+
if (nodeCrypto) {
|
|
13
|
+
if (typeof nodeCrypto.randomInt === "function") {
|
|
14
|
+
return nodeCrypto.randomInt(0, max);
|
|
15
|
+
}
|
|
16
|
+
if (typeof nodeCrypto.randomBytes === "function") {
|
|
17
|
+
return nodeCrypto.randomBytes(1)[0] % max;
|
|
8
18
|
}
|
|
9
|
-
|
|
10
|
-
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.getRandomValues) {
|
|
22
|
+
const arr = new Uint32Array(1);
|
|
23
|
+
globalThis.crypto.getRandomValues(arr);
|
|
24
|
+
return arr[0] % max;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return Math.floor(Math.random() * max);
|
|
11
28
|
}
|
|
12
29
|
|
|
13
30
|
function idchunk(length = 10, customValues = DEFAULT_VALUES) {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
31
|
+
if (typeof customValues !== "string" || customValues.length === 0) {
|
|
32
|
+
throw new Error("customValues must be a non-empty string");
|
|
33
|
+
}
|
|
17
34
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
35
|
+
let result = "";
|
|
36
|
+
for (let i = 0; i < length; i++) {
|
|
37
|
+
const randomIndex = getRandomInt(customValues.length);
|
|
38
|
+
result += customValues[randomIndex];
|
|
39
|
+
}
|
|
40
|
+
return result;
|
|
24
41
|
}
|
|
25
42
|
|
|
26
43
|
module.exports = idchunk;
|