Skip to content

Commit 7c28739

Browse files
committed
feat: String.random util
1 parent 4edc960 commit 7c28739

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

string/index.js

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ module.exports = {
55
"formatMethod": require("./format-method"),
66
"fromCodePoint": require("./from-code-point"),
77
"isString": require("./is-string"),
8+
"random": require("./random"),
89
"randomUniq": require("./random-uniq"),
910
"raw": require("./raw")
1011
};

string/random.js

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"use strict";
2+
3+
var isValue = require("../object/is-value")
4+
, toNaturalNumber = require("../number/to-pos-integer");
5+
6+
var generated = Object.create(null), random = Math.random, uniqTryLimit = 100;
7+
8+
var getChunk = function () {
9+
return random()
10+
.toString(36)
11+
.slice(2);
12+
};
13+
14+
var getString = function (/* length */) {
15+
var str = getChunk(), length = arguments[0];
16+
if (!isValue(length)) return str;
17+
while (str.length < length) str += getChunk();
18+
return str.slice(0, length);
19+
};
20+
21+
module.exports = function (/* options */) {
22+
var options = Object(arguments[0]), length = options.length, isUnique = options.isUnique;
23+
24+
if (isValue(length)) length = toNaturalNumber(length);
25+
26+
var str = getString(length);
27+
if (isUnique) {
28+
var count = 0;
29+
while (generated[str]) {
30+
if (++count === uniqTryLimit) {
31+
throw new Error(
32+
"Cannot generate random string.\n" +
33+
"String.random is not designed to effectively generate many short and " +
34+
"unique random strings"
35+
);
36+
}
37+
str = getString(length);
38+
}
39+
generated[str] = true;
40+
}
41+
return str;
42+
};

test/string/random.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
"use strict";
2+
3+
var isValidFormat = RegExp.prototype.test.bind(/^[a-z0-9]+$/);
4+
5+
module.exports = function (t, a) {
6+
a(typeof t(), "string");
7+
a.ok(t().length > 7);
8+
a.not(t({ isUnique: true }), t({ isUnique: true }));
9+
a.ok(isValidFormat(t()));
10+
a(t({ length: 1 }).length, 1);
11+
a(t({ length: 100 }).length, 100);
12+
a(t({ length: 0 }), "");
13+
};

0 commit comments

Comments
 (0)