diff options
| author | Marak <[email protected]> | 2017-09-08 16:01:22 -0400 |
|---|---|---|
| committer | GitHub <[email protected]> | 2017-09-08 16:01:22 -0400 |
| commit | d2bc3091e84ba03db44a6e76e938ecf307214a57 (patch) | |
| tree | 33dc1e1f45824fb94f739249406e68c6ae9b2aa2 /lib | |
| parent | aa8ac6cc11bb1be49dfd184289d45c8d9f420734 (diff) | |
| parent | fb8653c95016d393ccbbe6441f9952ed333d8e2d (diff) | |
| download | faker-d2bc3091e84ba03db44a6e76e938ecf307214a57.tar.xz faker-d2bc3091e84ba03db44a6e76e938ecf307214a57.zip | |
Merge pull request #366 from joonhocho/master
[api] Add `faker.random.arrayElements`
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/random.js | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/lib/random.js b/lib/random.js index 21151213..84c39911 100644 --- a/lib/random.js +++ b/lib/random.js @@ -69,6 +69,34 @@ function Random (faker, seed) { } /** + * takes an array and returns a subset with random elements of the array + * + * @method faker.random.arrayElement + * @param {array} array + * @param {number} count number of elements to pick + */ + this.arrayElements = function (array, count) { + array = array || ["a", "b", "c"]; + + if (typeof count !== 'number') { + count = faker.random.number({ min: 1, max: array.length }); + } else if (count > array.length) { + count = array.length; + } else if (count < 0) { + count = 0; + } + + var arrayCopy = array.slice(); + var countToRemove = arrayCopy.length - count; + for (var i = 0; i < countToRemove; i++) { + var indexToRemove = faker.random.number({ max: arrayCopy.length - 1 }); + arrayCopy.splice(indexToRemove, 1); + } + + return arrayCopy; + } + + /** * takes an object and returns the randomly key or value * * @method faker.random.objectElement |
