diff options
| author | Joon Ho Cho <[email protected]> | 2016-04-08 18:45:51 -0700 |
|---|---|---|
| committer | Joon Ho Cho <[email protected]> | 2016-04-08 18:45:51 -0700 |
| commit | fb8653c95016d393ccbbe6441f9952ed333d8e2d (patch) | |
| tree | f129b98b764784a4eeae4a01e827b8e6ac38f420 /lib/random.js | |
| parent | 649843ade73b730911506b8ecc6bf64bad10238c (diff) | |
| download | faker-fb8653c95016d393ccbbe6441f9952ed333d8e2d.tar.xz faker-fb8653c95016d393ccbbe6441f9952ed333d8e2d.zip | |
add faker.random.arrayElements
Diffstat (limited to 'lib/random.js')
| -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 d3cbf3ea..6b5544da 100644 --- a/lib/random.js +++ b/lib/random.js @@ -67,6 +67,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 |
