forked from fazlulkarimweb/custom-id
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (60 loc) Β· 1.86 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"use strict";
var cryptoRandom = require("math-random");
function idGenerate() {
var length =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 12;
var scope =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
if (typeof length !== "number") throw new Error("length must be a number");
if (typeof scope !== "string") throw new Error("scope must be a string");
var str = "";
var l = scope.length;
for (var i = 0; i < length; i++) {
str += scope.charAt(Math.floor(Math.random() * l));
}
return str;
}
module.exports = function customId(customId) {
if (typeof customId === "undefined") {
throw new Error(
"Custom Id expects an object as the argument. Make sure all values of that object are string."
);
}
var multiply = customId.uniqueId || 97232;
var crypticNotSecure = Math.floor(Math.random() * multiply);
var crypticSecureFun = cryptoRandom() * multiply;
var crypticSecure = Math.floor(crypticSecureFun);
var length = customId.randomLength || 2;
var firstId = idGenerate(
length,
crypticSecure.toString() || crypticNotSecure.toString()
);
if (customId.name) {
var name = idGenerate(
length,
customId.name.replace(/[^a-zA-Z0-9]/g, "").toString() || ""
);
} else {
var name = idGenerate(length, "ABCDEFGHIJKLMNOPQRSTUVXYZ");
}
if (customId.email) {
var email = idGenerate(
length,
customId.email.replace(/[^a-zA-Z0-9]/g, "").toString() || ""
);
} else {
var email = idGenerate(length, "ABCDEFGHIJKLMNOPQRSTUVXYZ");
}
var lastId = idGenerate(
length,
crypticSecure.toString() || crypticNotSecure.toString()
);
var result = firstId + name + lastId + email;
if (customId.lowerCase) {
return result.toLowerCase();
} else {
return result.toUpperCase();
}
};