From fb8653c95016d393ccbbe6441f9952ed333d8e2d Mon Sep 17 00:00:00 2001 From: Joon Ho Cho Date: Fri, 8 Apr 2016 18:45:51 -0700 Subject: add faker.random.arrayElements --- lib/random.js | 28 ++++++++++++++++++++++++++++ test/random.unit.js | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/lib/random.js b/lib/random.js index d3cbf3ea..6b5544da 100644 --- a/lib/random.js +++ b/lib/random.js @@ -66,6 +66,34 @@ function Random (faker, seed) { return array[r]; } + /** + * 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 * diff --git a/test/random.unit.js b/test/random.unit.js index 94a7167d..786cdc9b 100644 --- a/test/random.unit.js +++ b/test/random.unit.js @@ -89,6 +89,46 @@ describe("random.js", function () { }); }); + describe('arrayElements', function() { + it('returns a subset with random elements in the array', function() { + var testArray = ['hello', 'to', 'you', 'my', 'friend']; + var subset = faker.random.arrayElements(testArray); + + // Check length + assert.ok(subset.length >= 1 && subset.length <= testArray.length); + + // Check elements + subset.forEach(function(element) { + assert.ok(testArray.indexOf(element) > -1); + }); + + // Check uniqueness + subset.forEach(function(element) { + assert.ok(!this.hasOwnProperty(element)); + this[element] = true; + }, {}); + }); + + it('returns a subset of fixed length with random elements in the array', function() { + var testArray = ['hello', 'to', 'you', 'my', 'friend']; + var subset = faker.random.arrayElements(testArray, 3); + + // Check length + assert.ok(subset.length === 3); + + // Check elements + subset.forEach(function(element) { + assert.ok(testArray.indexOf(element) > -1); + }); + + // Check uniqueness + subset.forEach(function(element) { + assert.ok(!this.hasOwnProperty(element)); + this[element] = true; + }, {}); + }); + }); + describe('UUID', function() { it('should generate a valid UUID', function() { var UUID = faker.random.uuid(); -- cgit v1.2.3