Skip to content

Commit

Permalink
Merge pull request #7 from mankal111/getRandomElement
Browse files Browse the repository at this point in the history
Get random element
  • Loading branch information
mankal111 committed Oct 15, 2018
2 parents d3b6dbc + 4e54bf8 commit 76d960d
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ A possible value of `randomInterval` is `[43, 75]`.

The `minLength`, `maxLength` and `type` properties are optional.

To get a random element from a given array:

```js
var randomElement = JXRand.getElement([1, 2, 3]);
```

The `randomElement` should now contain one random element of the array.

## Tests
```
npm test
Expand Down
23 changes: 23 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ function checkIfOptionsIsObject(options) {
throw new TypeError(`Parameter's type is '${typeof options}' but it should be 'object'.`);
}

/**
* Checks if parameter is an array
* @param {array} array - The array parameter
* @returns {boolean} True if parameter is an array
*/
function checkIfParameterIsArray(array) {
if (Array.isArray(array)) {
return true;
}
throw new TypeError(`Parameter's type is '${typeof array}' but it should be 'array'.`);
}

/**
* Checks if min and max have the required values
* @param {object} options - The properties of the random number
Expand Down Expand Up @@ -78,9 +90,20 @@ function getInterval(options) {
return [leftEndpoint, rightEndpoint];
}

/**
* Returns a random element from given array
* @param {array} array - The array
* @returns The random element
*/
function getRandomElement(array) {
checkIfParameterIsArray(array);
return array[getNumber({ min: 0, max: array.length - 1, type: 'integer' })];
}

const JXRand = {
getNumber,
getInterval,
getRandomElement,
};

module.exports = JXRand;
11 changes: 11 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,14 @@ describe('getInterval', () => {
.to.throw(RangeError, "'burger' is not a supported type");
});
});

describe('getNumber', () => {
it('should throw an error if it is called without parameters', () => {
expect(() => JXRand.getRandomElement(1)).to.throw(TypeError, "Parameter's type is 'number' but it should be 'array'.");
});

it('should return an element of the given array', () => {
const givenArray = [1, 2, 3];
expect(givenArray.includes(JXRand.getRandomElement(givenArray))).to.equal(true);
});
});

0 comments on commit 76d960d

Please sign in to comment.