https://github.com/semibran/bag
Draw random items from a user-defined list
https://github.com/semibran/bag
bag random tetris
Last synced: about 1 year ago
JSON representation
Draw random items from a user-defined list
- Host: GitHub
- URL: https://github.com/semibran/bag
- Owner: semibran
- License: mit
- Created: 2017-02-01T04:35:22.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2017-02-10T23:26:48.000Z (over 9 years ago)
- Last Synced: 2025-02-12T18:59:29.104Z (over 1 year ago)
- Topics: bag, random, tetris
- Language: JavaScript
- Size: 3.91 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# bag
> Draw random items from a user-defined list
A rough implementation of the classic [**Random Generator**](http://tetris.wikia.com/wiki/Random_Generator) system from Tetris.
```javascript
const Bag = require('bag')
var fruits = ['apple', 'orange', 'banana']
var fruitBasket = Bag(fruits)
for (var i = 0, max = 10; i < max; i++) {
var fruit = fruitBasket.draw()
console.log(fruit)
}
```
Internally, each `Bag` instance has a `contents` array which turns out to be a shuffled version of the `items` initially passed. An item is removed from the bag each time `draw` is called. Once the bag is empty, the items are reshuffled and "poured" back into the bag. This process continues indefinitely as long as items are drawn from the bag's contents.
## Installation
```sh
npm install --save semibran/bag
```
## Usage
### Factory
```javascript
var bag = Bag(items, seed)
```
Creates a new `Bag` instance with the following parameters:
- `items`: An `Array` of elements to place into the bag.
- `seed`: A `Number` used to seed the bag's output. Use to coordinate the output of two separate `Bag` instances (e.g. providing the same piece sequence for two Tetris players)
### Methods
#### `draw`
```javascript
var randomItem = bag.draw()
```
#### `fill`
```javascript
bag = bag.fill() // Refill the bag until it is full enough to match `items.length`
```
## License
MIT