randomstring
Advanced tools
Comparing version 1.1.4 to 1.1.5
@@ -0,1 +1,5 @@ | ||
1.1.5 / May 18, 2016 | ||
================== | ||
* Optimized character generation algorithm | ||
1.1.4 / Feb 10, 2016 | ||
@@ -2,0 +6,0 @@ ================== |
@@ -6,2 +6,12 @@ "use strict"; | ||
function safeRandomBytes(length) { | ||
while (true) { | ||
try { | ||
return crypto.randomBytes(length); | ||
} catch(e) { | ||
continue; | ||
} | ||
} | ||
} | ||
exports.generate = function(options) { | ||
@@ -44,17 +54,16 @@ | ||
// Generate the string | ||
while (string.length < length) { | ||
var bf; | ||
try { | ||
bf = crypto.randomBytes(length); | ||
var charsLen = charset.chars.length; | ||
var maxByte = 256 - (256 % charsLen); | ||
while (length > 0) { | ||
var buf = safeRandomBytes(Math.ceil(length * 256 / maxByte)); | ||
for (var i = 0; i < buf.length && length > 0; i++) { | ||
var randomByte = buf.readUInt8(i); | ||
if (randomByte < maxByte) { | ||
string += charset.chars.charAt(randomByte % charsLen); | ||
length--; | ||
} | ||
} | ||
catch (e) { | ||
continue; | ||
} | ||
for (var i = 0; i < bf.length; i++) { | ||
var index = bf.readUInt8(i) % charset.chars.length; | ||
string += charset.chars.charAt(index); | ||
} | ||
} | ||
return string; | ||
} | ||
}; |
{ | ||
"name": "randomstring", | ||
"version": "1.1.4", | ||
"version": "1.1.5", | ||
"author": "Elias Klughammer <elias@klughammer.com> (http://www.klughammer.com)", | ||
@@ -5,0 +5,0 @@ "description": "A module for generating random strings", |
@@ -69,2 +69,33 @@ "use strict"; | ||
it("returns unique strings", function() { | ||
var results = {}; | ||
for (var i = 0; i < 1000; i++) { | ||
var s = random(); | ||
assert.notEqual(results[s], true); | ||
results[s] = true; | ||
} | ||
return true; | ||
}); | ||
it("returns unbiased strings", function() { | ||
var charset = 'abcdefghijklmnopqrstuvwxyz'; | ||
var slen = 100000; | ||
var s = random({ charset: charset, length: slen }); | ||
var counts = {}; | ||
for (var i = 0; i < s.length; i++) { | ||
var c = s.charAt(i); | ||
if (typeof counts[c] === "undefined") { | ||
counts[c] = 0; | ||
} else { | ||
counts[c]++; | ||
} | ||
} | ||
var avg = slen / charset.length; | ||
Object.keys(counts).sort().forEach(function(k) { | ||
var diff = counts[k] / avg; | ||
assert(diff > 0.95 && diff < 1.05, | ||
"bias on `" + k + "': expected average is " + avg + ", got " + counts[k]); | ||
}); | ||
}); | ||
}); |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
11241
183