-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Jonathan Keslin
committed
Jun 28, 2018
1 parent
bf19e8f
commit a3ce5a9
Showing
1 changed file
with
49 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,51 @@ | ||
# `random-from-collection` | ||
|
||
Get a random set of _n_ distinct values from a standard collection (i.e. Map, Set) | ||
Get a random set of _n_ distinct values from a standard collection (i.e. `Map`, `Set`). | ||
|
||
## Why? | ||
|
||
Types like `Map` and `Set` do not allow for access by index, so pulling a random set of values requires using an | ||
iterator. This pacakge handles that scenario. | ||
|
||
## API | ||
|
||
This package exports a single function that accepts a collection and a number of values to select. The collection can be | ||
any object that provides a `size` or `length` property/getter, and a `keys()` method that returns an iterator. In | ||
particular, it is useful for built-in types like Map and Set. | ||
|
||
It can be used on Arrays, but wouldn't really be very efficient, as Array allows for direct access by index so it is | ||
much faster to use a package like [`array-shuffle`](https://www.npmjs.com/package/array-shuffle) instead. | ||
|
||
## Usage | ||
|
||
```js | ||
const randomFromCollection = require('random-from-collection'); | ||
|
||
const mySet = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]); | ||
const setResults = randomFromCollection(mySet, 5); | ||
/* | ||
[1, 4, 6, 8, 9] | ||
*/ | ||
|
||
const myMap = new Map([ | ||
['a', 'A'], | ||
['b', 'B'], | ||
['c', 'C'] | ||
]); | ||
const mapResults = randomFromCollection(myMap, 2); | ||
/* | ||
['a', 'c'] | ||
*/ | ||
``` | ||
|
||
## Tests | ||
|
||
We have tests. You can run them for great justice. | ||
|
||
```sh | ||
npm test | ||
``` | ||
|
||
## Contributing | ||
|
||
Sure. Go ahead. Just remember to include tests. k thx. |