Repository: jonschlinkert/randomatic
Branch: master
Commit: 485a55248757
Files: 27
Total size: 37.2 KB
Directory structure:
gitextract_grrthyq4/
├── .editorconfig
├── .eslintrc.json
├── .gitattributes
├── .gitignore
├── .travis.yml
├── .verb.md
├── LICENSE
├── README.md
├── benchmark/
│ ├── .gitignore
│ ├── check.js
│ ├── code/
│ │ ├── current.js
│ │ └── for.js
│ ├── fixtures/
│ │ ├── 10.js
│ │ ├── 25-alpha-num.js
│ │ ├── 25.js
│ │ ├── 3.js
│ │ ├── 5.js
│ │ └── A-12.js
│ ├── index.js
│ └── last.md
├── bower.json
├── examples.js
├── index.d.ts
├── index.js
├── package.json
├── test.js
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
# http://editorconfig.org/
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[{**/{actual,fixtures,expected,templates}/**,*.md}]
trim_trailing_whitespace = false
insert_final_newline = false
================================================
FILE: .eslintrc.json
================================================
{
"env": {
"browser": false,
"es6": true,
"node": true,
"mocha": true
},
"parserOptions":{
"parser": "@typescript-eslint/parser",
"ecmaVersion": 2017,
"sourceType": "module",
"ecmaFeatures": {
"modules": true
}
},
"plugins": [
"@typescript-eslint/eslint-plugin"
],
"globals": {
"document": false,
"navigator": false,
"window": false
},
"rules": {
"accessor-pairs": 2,
"arrow-spacing": [2, { "before": true, "after": true }],
"block-spacing": [2, "always"],
"brace-style": [2, "1tbs", { "allowSingleLine": true }],
"comma-dangle": [2, "never"],
"comma-spacing": [2, { "before": false, "after": true }],
"comma-style": [2, "last"],
"constructor-super": 2,
"curly": [2, "multi-line"],
"dot-location": [2, "property"],
"eol-last": 2,
"eqeqeq": [2, "allow-null"],
"generator-star-spacing": [2, { "before": true, "after": true }],
"handle-callback-err": [2, "^(err|error)$" ],
"indent": [2, 2, { "SwitchCase": 1 }],
"key-spacing": [2, { "beforeColon": false, "afterColon": true }],
"keyword-spacing": [2, { "before": true, "after": true }],
"new-cap": [2, { "newIsCap": true, "capIsNew": false }],
"new-parens": 2,
"no-array-constructor": 2,
"no-caller": 2,
"no-class-assign": 2,
"no-cond-assign": 2,
"no-const-assign": 2,
"no-control-regex": 2,
"no-debugger": 2,
"no-delete-var": 2,
"no-dupe-args": 2,
"no-dupe-class-members": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-empty-character-class": 2,
"no-eval": 2,
"no-ex-assign": 2,
"no-extend-native": 2,
"no-extra-bind": 2,
"no-extra-boolean-cast": 2,
"no-extra-parens": [2, "functions"],
"no-fallthrough": 2,
"no-floating-decimal": 2,
"no-func-assign": 2,
"no-implied-eval": 2,
"no-inner-declarations": [2, "functions"],
"no-invalid-regexp": 2,
"no-irregular-whitespace": 2,
"no-iterator": 2,
"no-label-var": 2,
"no-labels": 2,
"no-lone-blocks": 2,
"no-mixed-spaces-and-tabs": 2,
"no-multi-spaces": 2,
"no-multi-str": 2,
"no-multiple-empty-lines": [2, { "max": 1 }],
"no-native-reassign": 0,
"no-negated-in-lhs": 2,
"no-new": 2,
"no-new-func": 2,
"no-new-object": 2,
"no-new-require": 2,
"no-new-wrappers": 2,
"no-obj-calls": 2,
"no-octal": 2,
"no-octal-escape": 2,
"no-proto": 0,
"no-redeclare": 2,
"no-regex-spaces": 2,
"no-return-assign": 2,
"no-self-compare": 2,
"no-sequences": 2,
"no-shadow-restricted-names": 2,
"no-spaced-func": 2,
"no-sparse-arrays": 2,
"no-this-before-super": 2,
"no-throw-literal": 2,
"no-trailing-spaces": 0,
"no-undef": 2,
"no-undef-init": 2,
"no-unexpected-multiline": 2,
"no-unneeded-ternary": [2, { "defaultAssignment": false }],
"no-unreachable": 2,
"no-unused-vars": [2, { "vars": "all", "args": "none" }],
"no-useless-call": 0,
"no-with": 2,
"one-var": [0, { "initialized": "never" }],
"operator-linebreak": [0, "after", { "overrides": { "?": "before", ":": "before" } }],
"padded-blocks": [0, "never"],
"quotes": [2, "single", "avoid-escape"],
"radix": 2,
"semi": [2, "always"],
"semi-spacing": [2, { "before": false, "after": true }],
"space-before-blocks": [2, "always"],
"space-before-function-paren": [2, "never"],
"space-in-parens": [2, "never"],
"space-infix-ops": 2,
"space-unary-ops": [2, { "words": true, "nonwords": false }],
"spaced-comment": [0, "always", { "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!", ","] }],
"use-isnan": 2,
"valid-typeof": 2,
"wrap-iife": [2, "any"],
"yoda": [2, "never"]
}
}
================================================
FILE: .gitattributes
================================================
# Enforce Unix newlines
*.* text eol=lf
*.css text eol=lf
*.html text eol=lf
*.js text eol=lf
*.json text eol=lf
*.less text eol=lf
*.md text eol=lf
*.yml text eol=lf
*.jpg binary
*.gif binary
*.png binary
*.jpeg binary
================================================
FILE: .gitignore
================================================
# always ignore files
*.DS_Store
.idea
.vscode
*.sublime-*
# test related, or directories generated by tests
test/actual
actual
coverage
.nyc*
# npm
node_modules
npm-debug.log
# yarn
yarn.lock
yarn-error.log
# misc
_gh_pages
_draft
_drafts
bower_components
vendor
temp
tmp
TODO.md
package-lock.json
================================================
FILE: .travis.yml
================================================
sudo: false
os:
- linux
- osx
language: node_js
node_js:
- node
- '9'
- '8'
- '7'
- '6'
- '5'
- '4'
- '0.12'
- '0.10'
================================================
FILE: .verb.md
================================================
## Usage
```js
var randomize = require('{%= name %}');
```
## API
```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
> The pattern to use for randomizing
Patterns can contain any combination of the below characters, specified in any order.
**Example:**
To generate a 10-character randomized string using all available characters:
```js
randomize('*', 10);
//=> 'x2_^-5_T[$'
randomize('Aa0!', 10);
//=> 'LV3u~BSGhw'
```
* `a`: Lowercase alpha characters (`abcdefghijklmnopqrstuvwxyz'`)
* `A`: Uppercase alpha characters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ'`)
* `0`: Numeric characters (`0123456789'`)
* `!`: Special characters (`~!@#$%^&()_+-={}[];\',.`)
* `*`: All characters (all of the above combined)
* `?`: Custom characters (pass a string of custom characters to the options)
### length
> The length of the string to generate
**Examples:**
* `randomize('A', 5)` will generate a 5-character, uppercase, alphabetical, randomized string, e.g. `KDJWJ`.
* `randomize('0', 2)` will generate a 2-digit random number
* `randomize('0', 3)` will generate a 3-digit random number
* `randomize('0', 12)` will generate a 12-digit random number
* `randomize('A0', 16)` will generate a 16-character, alpha-numeric randomized string
If `length` is left undefined, the length of the pattern in the first parameter will be used. For example:
* `randomize('00')` will generate a 2-digit random number
* `randomize('000')` will generate a 3-digit random number
* `randomize('0000')` will generate a 4-digit random number...
* `randomize('AAAAA')` will generate a 5-character, uppercase alphabetical random string...
These are just examples, [see the tests](./test.js) for more use cases and examples.
## options
> These are options that can be passed as the third argument.
#### chars
Type: `String`
Default: `undefined`
Define a custom string to be randomized.
**Example:**
* `randomize('?', 20, {chars: 'jonschlinkert'})` will generate a 20-character randomized string from the letters contained in `jonschlinkert`.
* `randomize('?', {chars: 'jonschlinkert'})` will generate a 13-character randomized string from the letters contained in `jonschlinkert`.
#### exclude
Type: `String|Array`
Default: `undefined`
Specify a string or array of characters can are excluded from the possible characters used to generate the randomized string.
**Example:**
* `randomize('*', 20, { exclude: '0oOiIlL1' })` will generate a 20-character randomized string using all of possible characters except for `0oOiIlL1`.
## Usage Examples
* `randomize('A', 4)` (_whitespace insenstive_) would result in randomized 4-digit uppercase letters, like, `ZAKH`, `UJSL`... etc.
* `randomize('AAAA')` is equivelant to `randomize('A', 4)`
* `randomize('AAA0')` and `randomize('AA00')` and `randomize('A0A0')` are equivelant to `randomize('A0', 4)`
* `randomize('aa')`: results in double-digit, randomized, lower-case letters (`abcdefghijklmnopqrstuvwxyz`)
* `randomize('AAA')`: results in triple-digit, randomized, upper-case letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`)
* `randomize('0', 6)`: results in six-digit, randomized numbers (`0123456789`)
* `randomize('!', 5)`: results in single-digit randomized, _valid_ non-letter characters (`~!@#$%^&()_+-={}[];\',.`)
* `randomize('A!a0', 9)`: results in nine-digit, randomized characters (any of the above)
_The order in which the characters are defined is insignificant._
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2013-2017, Jon Schlinkert.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# randomatic [](https://www.npmjs.com/package/randomatic) [](https://npmjs.org/package/randomatic) [](https://npmjs.org/package/randomatic) [](https://travis-ci.org/jonschlinkert/randomatic)
> Generate randomized strings of a specified length using simple character sequences. The original generate-password.
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save randomatic
```
## Usage
```js
var randomize = require('randomatic');
```
## API
```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
> The pattern to use for randomizing
Patterns can contain any combination of the below characters, specified in any order.
**Example:**
To generate a 10-character randomized string using all available characters:
```js
randomize('*', 10);
//=> 'x2_^-5_T[$'
randomize('Aa0!', 10);
//=> 'LV3u~BSGhw'
```
* `a`: Lowercase alpha characters (`abcdefghijklmnopqrstuvwxyz'`)
* `A`: Uppercase alpha characters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ'`)
* `0`: Numeric characters (`0123456789'`)
* `!`: Special characters (`~!@#$%^&()_+-={}[];\',.`)
* `*`: All characters (all of the above combined)
* `?`: Custom characters (pass a string of custom characters to the options)
### length
> The length of the string to generate
**Examples:**
* `randomize('A', 5)` will generate a 5-character, uppercase, alphabetical, randomized string, e.g. `KDJWJ`.
* `randomize('0', 2)` will generate a 2-digit random number
* `randomize('0', 3)` will generate a 3-digit random number
* `randomize('0', 12)` will generate a 12-digit random number
* `randomize('A0', 16)` will generate a 16-character, alpha-numeric randomized string
If `length` is left undefined, the length of the pattern in the first parameter will be used. For example:
* `randomize('00')` will generate a 2-digit random number
* `randomize('000')` will generate a 3-digit random number
* `randomize('0000')` will generate a 4-digit random number...
* `randomize('AAAAA')` will generate a 5-character, uppercase alphabetical random string...
These are just examples, [see the tests](./test.js) for more use cases and examples.
## options
> These are options that can be passed as the third argument.
#### chars
Type: `String`
Default: `undefined`
Define a custom string to be randomized.
**Example:**
* `randomize('?', 20, {chars: 'jonschlinkert'})` will generate a 20-character randomized string from the letters contained in `jonschlinkert`.
* `randomize('?', {chars: 'jonschlinkert'})` will generate a 13-character randomized string from the letters contained in `jonschlinkert`.
#### exclude
Type: `String|Array`
Default: `undefined`
Specify a string or array of characters can are excluded from the possible characters used to generate the randomized string.
**Example:**
* `randomize('*', 20, { exclude: '0oOiIlL1' })` will generate a 20-character randomized string using all of possible characters except for `0oOiIlL1`.
## Usage Examples
* `randomize('A', 4)` (_whitespace insensitive_) would result in randomized 4-digit uppercase letters, like, `ZAKH`, `UJSL`... etc.
* `randomize('AAAA')` is equivalent to `randomize('A', 4)`
* `randomize('AAA0')` and `randomize('AA00')` and `randomize('A0A0')` are equivalent to `randomize('A0', 4)`
* `randomize('aa')`: results in double-digit, randomized, lower-case letters (`abcdefghijklmnopqrstuvwxyz`)
* `randomize('AAA')`: results in triple-digit, randomized, upper-case letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`)
* `randomize('0', 6)`: results in six-digit, randomized numbers (`0123456789`)
* `randomize('!', 5)`: results in single-digit randomized, _valid_ non-letter characters (`~!@#$%^&()_+-={}[]
* `randomize('A!a0', 9)`: results in nine-digit, randomized characters (any of the above)
_The order in which the characters are defined is insignificant._
## About
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
Running Tests
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
Building docs
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
### Related projects
You might also be interested in these projects:
* [pad-left](https://www.npmjs.com/package/pad-left): Left pad a string with zeros or a specified string. Fastest implementation. | [homepage](https://github.com/jonschlinkert/pad-left "Left pad a string with zeros or a specified string. Fastest implementation.")
* [pad-right](https://www.npmjs.com/package/pad-right): Right pad a string with zeros or a specified string. Fastest implementation. | [homepage](https://github.com/jonschlinkert/pad-right "Right pad a string with zeros or a specified string. Fastest implementation.")
* [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.")
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 56 | [jonschlinkert](https://github.com/jonschlinkert) |
| 6 | [doowb](https://github.com/doowb) |
| 4 | [kivlor](https://github.com/kivlor) |
| 2 | [realityking](https://github.com/realityking) |
| 2 | [ywpark1](https://github.com/ywpark1) |
| 1 | [TrySound](https://github.com/TrySound) |
| 1 | [drag0s](https://github.com/drag0s) |
| 1 | [paulmillr](https://github.com/paulmillr) |
| 1 | [sunknudsen](https://github.com/sunknudsen) |
| 1 | [faizulhaque-tp](https://github.com/faizulhaque-tp) |
| 1 | [michaelrhodes](https://github.com/michaelrhodes) |
### Author
**Jon Schlinkert**
* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
### License
Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on October 23, 2018._
================================================
FILE: benchmark/.gitignore
================================================
*.DS_Store
================================================
FILE: benchmark/check.js
================================================
'use strict';
var bold = require('ansi-bold');
var path = require('path');
var glob = require('glob');
/**
* Sanity check. Run to ensure that all fns return the same result.
*/
var fixtures = glob.sync(__dirname + '/fixtures/*.js');
glob.sync(__dirname + '/code/*.js').forEach(function (fp) {
if (/\.js/.test(fp)) {
var fn = require(path.resolve(__dirname, 'code', fp));
var name = path.basename(fp, path.extname(fp));
if (/.*/.test(name)) {
fixtures.forEach(function (fixture) {
if (/^.*\.js/.test(path.basename(fixture))) {
console.log(bold(name) + ':', fn.apply(fn, require(fixture)));
}
});
}
}
});
================================================
FILE: benchmark/code/current.js
================================================
'use strict';
module.exports = require('../..');
================================================
FILE: benchmark/code/for.js
================================================
/*!
* randomatic
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License (MIT)
*
* Many changes have been made, but this was originally
* inspired by
*/
'use strict';
var isNumber = require('is-number');
var typeOf = require('kind-of');
/**
* Expose `randomatic`
*/
module.exports = randomatic;
/**
* Available mask characters
*/
var type = {
lower: 'abcdefghijklmnopqrstuvwxyz',
upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
number: '0123456789',
special: '~!@#$%^&()_+-={}[];\',.'
};
type.all = type.lower + type.upper + type.number;
/**
* Generate random character sequences of a specified `length`,
* based on the given `pattern`.
*
* @param {String} `pattern` The pattern to use for generating the random string.
* @param {String} `length` The length of the string to generate.
* @param {String} `options`
* @return {String}
* @api public
*/
function randomatic(pattern, length, options) {
if (typeof pattern === 'undefined') {
throw new Error('randomatic expects a string or number.');
}
var custom = false;
if (arguments.length === 1) {
if (typeof pattern === 'string') {
length = pattern.length;
} else if (isNumber(pattern)) {
options = {};
length = pattern;
pattern = '*';
}
}
if(typeOf(length) === 'object' && length.hasOwnProperty('chars')) {
options = length;
pattern = options.chars;
length = pattern.length;
custom = true;
}
var opts = options || {};
var mask = '';
var res = '';
// Characters to be used
if (pattern.indexOf('?') !== -1) mask += opts.chars;
if (pattern.indexOf('a') !== -1) mask += type.lower;
if (pattern.indexOf('A') !== -1) mask += type.upper;
if (pattern.indexOf('0') !== -1) mask += type.number;
if (pattern.indexOf('!') !== -1) mask += type.special;
if (pattern.indexOf('*') !== -1) mask += type.all;
if (custom) mask += pattern;
for (var i = 0; i < length; i++) {
res += mask.charAt(parseInt(Math.random() * mask.length));
}
return res;
};
================================================
FILE: benchmark/fixtures/10.js
================================================
module.exports = ['*', 10];
================================================
FILE: benchmark/fixtures/25-alpha-num.js
================================================
module.exports = ['0aA', 25];
================================================
FILE: benchmark/fixtures/25.js
================================================
module.exports = ['*', 25];
================================================
FILE: benchmark/fixtures/3.js
================================================
module.exports = ['*', 3];
================================================
FILE: benchmark/fixtures/5.js
================================================
module.exports = ['*', 5];
================================================
FILE: benchmark/fixtures/A-12.js
================================================
module.exports = ['A', 12];
================================================
FILE: benchmark/index.js
================================================
'use strict';
var Suite = require('benchmarked');
var suite = new Suite({
result: false,
fixtures: 'fixtures/*.js',
add: 'code/*.js',
cwd: __dirname
});
suite.run();
================================================
FILE: benchmark/last.md
================================================
# 20,000x
repeat-string.js x 16,619,408 ops/sec ±1.05% (92 runs sampled)
repeating.js x 5,991,724 ops/sec ±0.62% (98 runs sampled)
# 2,000x
repeat-string.js x 17,284,768 ops/sec ±0.71% (94 runs sampled)
repeating.js x 6,828,993 ops/sec ±0.87% (96 runs sampled)
# 250x
repeat-string.js x 16,241,986 ops/sec ±0.78% (93 runs sampled)
repeating.js x 7,281,492 ops/sec ±0.76% (95 runs sampled)
# 50x
repeat-string.js x 16,447,301 ops/sec ±1.12% (96 runs sampled)
repeating.js x 8,933,633 ops/sec ±0.64% (98 runs sampled)
# 5x
repeat-string.js x 16,363,515 ops/sec ±1.09% (98 runs sampled)
repeating.js x 12,164,964 ops/sec ±0.74% (98 runs sampled)
================================================
FILE: bower.json
================================================
{
"name": "randomatic",
"description": "Generate randomized strings of a specified length using simple character sequences. The original generate-password.",
"repository": "jonschlinkert/randomatic",
"license": "MIT",
"homepage": "https://github.com/jonschlinkert/randomatic",
"authors": [
"Jon Schlinkert (https://github.com/jonschlinkert)"
],
"main": [
"index.js"
],
"dependencies": {
"is-number": "^4.0.0",
"kind-of": "^6.0.0",
"math-random": "^1.0.1"
},
"devDependencies": {
"ansi-bold": "^0.1.1",
"benchmarked": "^1.1.1",
"glob": "^7.1.2",
"gulp-format-md": "^0.1.12",
"mocha": "^3.4.2"
},
"keywords": [
"alpha",
"alpha-numeric",
"alphanumeric",
"characters",
"chars",
"generate",
"generate-password",
"numeric",
"password",
"rand",
"random",
"randomatic",
"randomize",
"randomized"
],
"version": "2.0.0",
"bugs": {
"url": "https://github.com/jonschlinkert/randomatic/issues"
},
"files": [
"index.js"
],
"ignore": [
"actual",
"bower_components",
"fixtures",
"node_modules",
"temp",
"test",
"test.js",
"tmp"
],
"contributors": [
"Bogdan Chadkin (https://github.com/TrySound)",
"Dragos Fotescu (http://dragosfotescu.com)",
"Faiz ul haque (http://www.10pearls.com)",
"Jon Schlinkert (http://twitter.com/jonschlinkert)",
"Paul Miller (paulmillr.com)",
"Rouven Weßling (www.rouvenwessling.de)",
"Sun Knudsen (https://sunknudsen.com)"
]
}
================================================
FILE: examples.js
================================================
'use strict';
var rand = require('./');
// Example replacement patterns.
var replacements = [{
pattern: /:random\(([^)]*)\)/,
replacement: function (match, args) {
if(args.match(/,/)) {
args = parse(args.split(','));
// console.log(args)
return rand.apply(rand, args);
} else {
return rand(args);
}
}
}];
function randomize(patterns, arr) {
var keys = Object.keys(patterns);
return keys.reduce(function(res, str) {
var desc = patterns[str];
var result = arr.reduce(function(acc, o) {
return acc.replace(o.pattern, o.replacement);
}, str);
res[desc] = {};
res[desc].result = result;
res[desc].length = result.length;
return res;
}, {});
}
var patterns = {
// Pattern // Should result in...
':random(A, 10)' : 'alpha, (10 digits)',
':random(A, 5)' : 'alpha, (5 digits)',
':random(7, {chars: "foo\'s"})' : 'special chars, (7 digits)',
':random(AA, 10)' : 'alpha, (10 digits)',
':random(Aa, 12)' : 'alpha, (12 digits)',
':random(A, 3)' : 'alpha, (3 digits)',
':random(AAa)' : 'alpha, (3 digits)',
':random(AA, 3)' : 'alpha, (3 digits)',
':random(A0, 5)' : 'alpha-numeric, (5 digits)',
':random(AA00, 5)' : 'alpha-numeric, (5 digits)',
':random(A0A0, 5)' : 'alpha-numeric, (5 digits)',
':random(AaAa0000)' : 'alpha-numeric, (8 digits)',
':random(0, 1)' : 'numeric, (1 digit)',
':random(0, 8)' : 'numeric, (8 digits)',
':random(00000000)' : 'numeric, (8 digits)',
':random(A0!, 7)' : 'special chars, (7 digits)',
':random(A0!a0A0)' : 'special chars, (7 digits)',
':random(Aa0, 1)' : 'alpha, (1 digit)',
':random(*, 16)' : 'all characters, (16 digits)',
':random(?, 16, jonathan)' : 'custom chars, (16 digit)'
};
console.log(randomize(patterns, replacements));
function parse(args) {
return args.map(function(arg) {
if (/\{/.test(arg)) {
var start = /(['"])/;
var i = arg.search(start);
var ch = arg[i];
var match;
var chars = '';
while ((match = arg.charAt(++i)) !== ch) {
chars += match;
}
console.log(chars);
return {chars: chars};
}
return arg;
});
}
console.log();
console.log(rand('*', 20, { exclude: '0oOiIlL1' }));
console.log();
// function parse(args) {
// return args.map(function(arg) {
// if (/\{/.test(arg)) {
// var match = /['"]([^"']+)["']/.exec(arg);
// if (match) {
// return {chars: match[1]};
// }
// }
// return arg;
// });
// }
================================================
FILE: index.d.ts
================================================
// Type definitions for randomatic 3.1
// Project: https://github.com/jonschlinkert/randomatic
// Definitions by: Sang Dang
interface Options {
chars?: string;
exclude?: string | string[];
}
declare function randomatic(pattern: string, length?: number, options?: Options): string;
declare namespace randomatic {
const isCrypto: boolean;
}
export = randomatic;
================================================
FILE: index.js
================================================
/*!
* randomatic
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
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
*/
var type = {
lower: 'abcdefghijklmnopqrstuvwxyz',
upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
number: '0123456789',
special: '~!@#$%^&()_+-={}[];\',.'
};
type.all = type.lower + type.upper + type.number + type.special;
/**
* Generate random character sequences of a specified `length`,
* based on the given `pattern`.
*
* @param {String} `pattern` The pattern to use for generating the random string.
* @param {String} `length` The length of the string to generate.
* @param {String} `options`
* @return {String}
* @api public
*/
function randomatic(pattern, length, options) {
if (typeof pattern === 'undefined') {
throw new Error('randomatic expects a string or number.');
}
var custom = false;
if (arguments.length === 1) {
if (typeof pattern === 'string') {
length = pattern.length;
} else if (isNumber(pattern)) {
options = {};
length = pattern;
pattern = '*';
}
}
if (typeOf(length) === 'object' && length.hasOwnProperty('chars')) {
options = length;
pattern = options.chars;
length = pattern.length;
custom = true;
}
var opts = options || {};
var mask = '';
var res = '';
// Characters to be used
if (pattern.indexOf('?') !== -1) mask += opts.chars;
if (pattern.indexOf('a') !== -1) mask += type.lower;
if (pattern.indexOf('A') !== -1) mask += type.upper;
if (pattern.indexOf('0') !== -1) mask += type.number;
if (pattern.indexOf('!') !== -1) mask += type.special;
if (pattern.indexOf('*') !== -1) mask += type.all;
if (custom) mask += pattern;
// Characters to exclude
if (opts.exclude) {
var exclude = typeOf(opts.exclude) === 'string' ? opts.exclude : opts.exclude.join('');
exclude = exclude.replace(new RegExp('[\\]]+', 'g'), '');
mask = mask.replace(new RegExp('[' + exclude + ']+', 'g'), '');
if(opts.exclude.indexOf(']') !== -1) mask = mask.replace(new RegExp('[\\]]+', 'g'), '');
}
while (length--) {
res += mask.charAt(parseInt(mathRandom() * mask.length, 10));
}
return res;
};
================================================
FILE: package.json
================================================
{
"name": "randomatic",
"description": "Generate randomized strings of a specified length using simple character sequences. The original generate-password.",
"version": "3.1.1",
"homepage": "https://github.com/jonschlinkert/randomatic",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"contributors": [
"Bogdan Chadkin (https://github.com/TrySound)",
"Dragos Fotescu (http://dragosfotescu.com)",
"Faiz ul haque (http://www.10pearls.com)",
"Jon Schlinkert (http://twitter.com/jonschlinkert)",
"Michael Rhodes (http://michaelrhod.es)",
"Paul Miller (https://paulmillr.com)",
"Rouven Weßling (www.rouvenwessling.de)",
"Sun Knudsen (https://sunknudsen.com)"
],
"repository": "jonschlinkert/randomatic",
"bugs": {
"url": "https://github.com/jonschlinkert/randomatic/issues"
},
"license": "MIT",
"files": [
"index.js"
],
"main": "index.js",
"engines": {
"node": ">= 0.10.0"
},
"scripts": {
"test": "mocha"
},
"dependencies": {
"is-number": "^4.0.0",
"kind-of": "^6.0.0",
"math-random": "^1.0.1"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^1.11.0",
"@typescript-eslint/parser": "^1.11.0",
"ansi-bold": "^0.1.1",
"benchmarked": "^1.1.1",
"glob": "^7.1.2",
"gulp-format-md": "^0.1.12",
"mocha": "^3.4.2"
},
"keywords": [
"alpha",
"alpha-numeric",
"alphanumeric",
"characters",
"chars",
"generate",
"generate-password",
"numeric",
"password",
"rand",
"random",
"randomatic",
"randomize",
"randomized"
],
"verb": {
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"related": {
"list": [
"pad-left",
"pad-right",
"repeat-string"
]
},
"lint": {
"reflinks": true
}
}
}
================================================
FILE: test.js
================================================
/**
* randomatic
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT license.
*/
'use strict';
require('mocha');
var assert = require('assert');
var randomize = require('./');
function test(re, str) {
return re.test(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();
}, /randomatic expects a string or number\./);
});
it('should generate a randomized string of the given length:', function() {
assert.equal(randomize(12).length, 12);
assert.equal(typeof randomize(5), 'string');
});
it('should generate a string with a length equal to the number passed as a second parameter', function() {
var actual = randomize('A', 12);
assert.equal(actual.length, 12);
assert(test(/[A-Z]{12}/, actual));
});
it('should generate a 12-character string, lowercase', function() {
var actual = randomize('a', 12);
assert(test(/[a-z]{12}/, actual));
assert.equal(actual.length, 12);
});
it('should generate 12-characters of ordered numbers', function() {
var actual = randomize('0', 12);
assert(test(/[\d]{12}/, actual));
assert(!test(/[\d]{13}/, actual));
assert.equal(actual.length, 12);
});
it('should generate a randomized 12-character string, uppercase and numbers', function() {
var actual = randomize('A0', 12);
assert(test(/[\dA-Z]{12}/, actual));
assert(!test(/[\dA-Z]{13}/, actual));
assert.equal(actual.length, 12);
});
it('should generate a 3-character string, all uppercase letters', function() {
assert(test(/[A-Z]{3}/, randomize('AAA')));
assert(!test(/[a-z]{3}/, randomize('AAA')));
assert.equal(randomize('AAA').length, 3);
assert(test(/[A-Z]{3}/, randomize('AAAAA', 3)));
assert(!test(/[a-z]{3}/, randomize('AAAAA', 3)));
assert.equal(randomize('AAAAA', 3).length, 3);
});
it('should generate an 12-character string of random uppercase and lowercase letters, and numbers', function() {
var actual = randomize('Aa0', 12);
assert.equal(actual.length, 12);
assert(test(/[\dA-Za-z]{3}/, actual));
});
it('should generate an 3-character, random alpha-numeric string', function() {
var actual = randomize('Aa0');
assert(test(/[\dA-Za-z]{3}/, actual));
assert.equal(actual.length, 3);
});
it('should generate 3-characters of numbers in order', function() {
var actual = randomize('000');
assert(test(/\d{3}/, actual));
assert.equal(actual.length, 3);
});
it('should randomize a string from the characters on the `chars` option', function() {
var actual = randomize('?', {chars: 'jonschlinkert'});
assert(test(/[jonschlinkert]{13}/, actual));
assert.equal(actual.length, 13);
});
it('should generate a random string excluding characters on the `exclude` option', function() {
var actual = randomize('?', 16, {chars: 'jonschlinkert', exclude: '0Oo'});
assert(test(/[^oO0]{16}/, actual));
assert.equal(actual.length, 16);
});
it('should generate a random string excluding array of characters on the `exclude` option', function() {
var actual = randomize('?', 16, {chars: 'jonschlinkert', exclude: ['0','O','o']});
assert(test(/[^oO0]{16}/, actual));
assert.equal(actual.length, 16);
});
it('should generate a random string excluding right square bracket on the `exclude` option', function() {
var actual = randomize('*', 16, {exclude: ']'});
assert(test(/[^\]]{16}/, actual));
assert.equal(actual.length, 16);
});
it('should generate a random string excluding array with one element(right square bracket) on the `exclude` option', function() {
var actual = randomize('*', 16, {exclude: [']']});
assert(test(/[^\]]{16}/, actual));
assert.equal(actual.length, 16);
});
it('should generate a radomized 16-character string', function() {
assert.equal(randomize('*', 16).length, 16);
});
it('should generate Alpha (Upper/Lower), Numeric, Special Char 16-character string', function() {
var actual = randomize('*');
assert(test(/^[-~!@#$%^&()_+={}[\];\',.a-zA-Z0-9]$/, actual));
});
it('alphabetical, 10 digit:', function() {
assert.equal(randomize('A', 10).length, 10);
});
it('alphabetical, 5 digits:', function() {
var actual = randomize('A', 5);
assert(test(/[A-Z]{5}/, actual));
assert.equal(actual.length, 5);
});
it('alphabetical, 10 digits:', function() {
var actual = randomize('AA', 10);
assert(test(/[A-Z]{10}/, actual));
assert.equal(actual.length, 10);
});
it('alphabetical, 12 digits:', function() {
var actual = randomize('Aa', 12);
assert.equal(actual.length, 12);
});
it('alphabetical, 3 digits:', function() {
var actual = randomize('A', 3);
assert(test(/[A-Z]{3}/, actual));
assert.equal(actual.length, 3);
});
it('alphabetical, 3 digits:', function() {
var actual = randomize('AAa');
assert(test(/[A-Za-z]{3}/, actual));
assert.equal(actual.length, 3);
});
it('alphabetical, 3 digits:', function() {
var actual = randomize('AA', 3);
assert(test(/[A-Z]{3}/, actual));
assert.equal(actual.length, 3);
});
it('alphabetical, 3 digits:', function() {
var actual = randomize('AA');
assert(test(/[A-Z]{2}/, actual));
assert.equal(actual.length, 2);
});
it('alpha-numeric, 5 digits:', function() {
var actual = randomize('A0', 5);
assert(test(/[A-Z\d]{5}/, actual));
assert.equal(actual.length, 5);
});
it('alpha-numeric, 5 digits:', function() {
var actual = randomize('AA00', 5);
assert(test(/[A-Z\d]{5}/, actual));
assert.equal(actual.length, 5);
});
it('alpha-numeric, 5 digits:', function() {
var actual = randomize('A0A0', 5);
assert(test(/[A-Z\d]{5}/, actual));
assert.equal(actual.length, 5);
});
it('alpha-numeric, 5 digits:', function() {
var actual = randomize('A0A0A0A0A0A', 5);
assert(test(/[A-Z\d]{5}/, actual));
assert.equal(actual.length, 5);
});
it('alpha-numeric, 8 digits:', function() {
var actual = randomize('AaAa0000');
assert(test(/[A-Za-z0-9]{8}/, actual));
assert.equal(actual.length, 8);
});
it('numeric, 1 digit:\t', function() {
var actual = randomize('0', 1);
assert(test(/\d{1}/, actual));
assert.equal(actual.length, 1);
});
it('numeric, 8 digits:\t', function() {
var actual = randomize('0', 8);
assert(test(/^\d{8}/, actual));
assert.equal(actual.length, 8);
});
it('numeric, 8 digits:\t', function() {
var actual = randomize('00000000');
assert(test(/^\d{8}/, actual));
assert.equal(actual.length, 8);
});
it('special chars, 7 digits:', function() {
var actual = randomize('A0!', 7);
assert(test(/[\s\S]{7}/, actual));
assert.equal(actual.length, 7);
});
it('special chars, 7 digits:', function() {
var actual = randomize('A0!a0A0');
assert(test(/[\s\S]{7}/, actual));
assert(!test(/[\s\S]{8}/, actual));
assert.equal(actual.length, 7);
});
it('alphabetical, 1 digit:', function() {
var actual = randomize('Aa0');
assert(test(/[A-Za-z0-9]{3}/, actual));
assert.equal(actual.length, 3);
});
it('all characters, 16 digits:', function() {
assert.equal(randomize('*', 16).length, 16);
});
it('custom chars, 16 digit', function() {
var actual = randomize('?', 16, {chars: 'jonathan'});
assert(test(/[jonathan]/, actual));
assert.equal(actual.length, 16);
});
});
================================================
FILE: tsconfig.json
================================================
{
"compilerOptions": {
"allowJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"module": "commonjs",
"declarationMap": true,
"rootDir": ".",
"target": "es2017"
},
"include": [
"index.js"
]
}