Skip to content

semibran/bag

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

bag

Draw random items from a user-defined list

A rough implementation of the classic Random Generator system from Tetris.

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

npm install --save semibran/bag

Usage

Factory

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

var randomItem = bag.draw()

fill

bag = bag.fill() // Refill the bag until it is full enough to match `items.length`

License

MIT

About

Draw random items from a user-defined list

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published