@smakss/random-array-element
TypeScript icon, indicating that this package has built-in type declarations

2.0.3 • Public • Published

Random Array Element without Repetition

npm NPM npm npm bundle size (scoped)

Selecting a random element from an array is simple with Math.random(). However, if you need to ensure that each element is only selected once until all elements have been chosen, @smakss/random-array-element is the ideal solution. Utilizing closures, this package allows you to initialize a function once and then repeatedly obtain unique, randomly-selected elements from your array, without repeats until the array is exhausted.

Demo

You can check the working demo on RunKit.

or

View @smakss/random-array-element

Installation

Install the package using npm or Yarn:

npm i @smakss/random-array-element
# or
yarn add @smakss/random-array-element

Usage

To include it with CommonJS module you can do this:

const randomArrayElement = require('@smakss/random-array-element');

For ECMAScript modules:

import randomArrayElement from '@smakss/random-array-element';

Example usage:

// Initialize once for an array
const getRandomElement = randomArrayElement(['apple', 'banana', 'cherry']);

console.log(getRandomElement()); // Result: 'banana' (example output)
console.log(getRandomElement()); // Result: 'apple' (example output)
// ...after all items have been returned, it resets.
console.log(getRandomElement()); // Result: 'cherry' (example output)
// ...continues to return a new random item.

If an empty or non-array input is passed, the function will return -1, indicating no selection can be made:

const getRandomElement = randomArrayElement([]);
console.log(getRandomElement()); // Result: -1

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines and details.

Code of Conduct

To ensure a welcoming and safe community, our Code of Conduct outlines expected behaviors for all participants.

Package Sidebar

Install

npm i @smakss/random-array-element

Weekly Downloads

2

Version

2.0.3

License

MIT

Unpacked Size

14.5 kB

Total Files

9

Last publish

Collaborators

  • smakss