Skip to content

melkir/random-iterator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

random-iterator Build Status codecov

Iterate values in a list in random order using ES6 Generator

Install

$ npm install random-iterator

Usage

Simple Array

const randomIterator = require('random-iterator');

const it = randomIterator([1, 2, 3]);

it.next(); // => { value: 3, done: false }
it.next(); // => { value: 1, done: false }
it.next(); // => { value: 2, done: false }
it.next(); // => { value: undefined, done: true }

Objects

const quotesIterable = randomIterator({
  a: 'hi',
  b: 'hello',
  c: 'good morning',
});

// Randomly pick a quote
quotesIterable.next().value; // => hello

Deck of cards

const generateDeck = () => {
  const suits = ['♣', '♦', '♥', '♠'];
  const symbols = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
  const deck = [];

  for (let su = 0; su < suits.length; ++su) {
    for (let sy = 0; sy < symbols.length; ++sy) {
      const suit = suits[su];
      const symbol = symbols[sy];
      deck.push(`${symbol} ${suit}`);
    }
  }

  return deck;
};

// Create a deck of cards
const myDeck = generateDeck();

// Randomly draw a card inside the deck
const deckIterable = randomIterator(myDeck);
deckIterable.next().value; // => Q ♥
deckIterable.next().value; // => 4 ♣
deckIterable.next().value; // => 7 ♣

License

MIT © Thibaut Vieux

About

Iterate values in a list in random order

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published