Skip to content

Commit

Permalink
use cryptographically secure random function
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelrhodes committed Dec 22, 2017
1 parent 833f31a commit 4a52695
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .verb.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ var randomize = require('{%= name %}');

```js
randomize(pattern, length, options);
randomize.isCrypto;
```

- `pattern` **{String}**: (required) The pattern to use for randomizing
- `length` **{Number}**: (optional) The length of the string to generate
- `options` **{Object}**: (optional) See available [options](#options)

- `randomize.isCrypto` will be `true` when a cryptographically secure function is being used to generate random numbers. The value will be `false` when the function in use is `Math.random`.

### pattern

Expand Down
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@

var isNumber = require('is-number');
var typeOf = require('kind-of');
var mathRandom = require('math-random');

/**
* Expose `randomatic`
*/

module.exports = randomatic;
module.exports.isCrypto = !!mathRandom.cryptographic;

/**
* Available mask characters
Expand Down Expand Up @@ -78,7 +80,7 @@ function randomatic(pattern, length, options) {
if (custom) mask += pattern;

while (length--) {
res += mask.charAt(parseInt(Math.random() * mask.length, 10));
res += mask.charAt(parseInt(mathRandom() * mask.length, 10));
}
return res;
};
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
},
"dependencies": {
"is-number": "^4.0.0",
"kind-of": "^6.0.0"
"kind-of": "^6.0.0",
"math-random": "^1.0.1"
},
"devDependencies": {
"ansi-bold": "^0.1.1",
Expand Down
4 changes: 4 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ function test(re, str) {
}

describe('randomatic', function() {
it('should export an isCrypto boolean property', function() {
assert.equal(typeof randomize.isCrypto, 'boolean');
});

it('should throw an error when no arguments are passed:', function() {
assert.throws(function() {
randomize();
Expand Down

0 comments on commit 4a52695

Please sign in to comment.