Skip to content

Commit

Permalink
[doc] Helps to include a README
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonathan Keslin committed Jun 28, 2018
1 parent bf19e8f commit a3ce5a9
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion README.md
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.

0 comments on commit a3ce5a9

Please sign in to comment.