Skip to content

Commit

Permalink
Merge pull request #366 from joonhocho/master
Browse files Browse the repository at this point in the history
[api] Add `faker.random.arrayElements`
  • Loading branch information
Marak authored Sep 8, 2017
2 parents aa8ac6c + fb8653c commit d2bc309
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,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
*
Expand Down
40 changes: 40 additions & 0 deletions test/random.unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,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();
Expand Down

0 comments on commit d2bc309

Please sign in to comment.