Skip to content

Commit

Permalink
Merge 7146b0a into c629897
Browse files Browse the repository at this point in the history
  • Loading branch information
hugoiuri committed Jul 3, 2019
2 parents c629897 + 7146b0a commit 0474716
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
9 changes: 7 additions & 2 deletions chance.js
Expand Up @@ -406,12 +406,17 @@
/**
* Return a random string
*
* @param {Object} [options={}] can specify a length
* @param {Object} [options={}] can specify a length or min and max
* @returns {String} a string of random length
* @throws {RangeError} length cannot be less than zero
*/
Chance.prototype.string = function (options) {
options = initOptions(options, { length: this.natural({min: 5, max: 20}) });
options = initOptions(options, { min: 5, max: 20 });

if (!options.length) {
options.length = this.natural({ min: options.min, max: options.max })
}

testRange(options.length < 0, "Chance: Length cannot be less than zero.");
var length = options.length,
text = this.n(this.character, length, options);
Expand Down
24 changes: 23 additions & 1 deletion docs/basics/string.md
Expand Up @@ -4,6 +4,9 @@
// usage
chance.string()
chance.string({ length: 5 })
chance.string({ min: 5 })
chance.string({ max: 50 })
chance.string({ min: 5, max: 20 })
chance.string({ pool: 'abcde' })
```

Expand All @@ -28,6 +31,20 @@ Can optionally specify a length and the string will be exactly that length.
=> 'YN%fG'
```

Can optionally specify a min and the string will have a minimum lentgh

```js
chance.string({ min: 5 });
=> '6(Ow1wF)qjUm%W)B2[Q]'
```

Can optionally specify a max and the string will have a maximum lentgh

```js
chance.string({ max: 20 });
=> 'k7fubkfMS@gs#E'
```

Can optionally specify a pool and the string will be generated with characters
only from that pool.

Expand All @@ -36,9 +53,14 @@ only from that pool.
=> 'cccdeeabedebb'
```

Of course these options can also be combined.
Of course these options can also be combined, using length or min and max.

```js
chance.string({ length: 5, pool: 'abcde' });
=> 'cbbdc'
```

```js
chance.string({ min: 5, max: 20, pool: 'abcde' });
=> 'ebddceaaceeda'
```
12 changes: 12 additions & 0 deletions test/test.basic.js
Expand Up @@ -504,6 +504,18 @@ test('string() obeys symbol', t => {
})
})

test('string() can take just a min and obey it', t => {
_.times(1000, () => {
t.true(chance.string({ min: 6 }).length >= 6)
})
})

test('string() can take just a max and obey it', t => {
_.times(1000, () => {
t.true(chance.string({ max: 20 }).length <= 20)
})
})

test('falsy() should return a falsy value', t => {
_.times(1000, () => {
const value = chance.falsy()
Expand Down

0 comments on commit 0474716

Please sign in to comment.