File tree 3 files changed +56
-0
lines changed
3 files changed +56
-0
lines changed Original file line number Diff line number Diff line change @@ -5,6 +5,7 @@ module.exports = {
5
5
"formatMethod" : require ( "./format-method" ) ,
6
6
"fromCodePoint" : require ( "./from-code-point" ) ,
7
7
"isString" : require ( "./is-string" ) ,
8
+ "random" : require ( "./random" ) ,
8
9
"randomUniq" : require ( "./random-uniq" ) ,
9
10
"raw" : require ( "./raw" )
10
11
} ;
Original file line number Diff line number Diff line change
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
+ } ;
Original file line number Diff line number Diff line change
1
+ "use strict" ;
2
+
3
+ var isValidFormat = RegExp . prototype . test . bind ( / ^ [ a - z 0 - 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
+ } ;
You can’t perform that action at this time.
0 commit comments