2.0.3 • Published 1 year ago

@smakss/random-array-element v2.0.3

Weekly downloads
11
License
MIT
Repository
github
Last release
1 year ago

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.

2.0.3

1 year ago

2.0.2

2 years ago

2.0.1

2 years ago

2.0.0

2 years ago

2.0.2-beta.0

2 years ago

2.0.0-beta.0

2 years ago

1.2.5

2 years ago

1.2.4

3 years ago

1.2.3

3 years ago

1.2.2

4 years ago

1.2.1

4 years ago

1.2.0

4 years ago

1.1.27

4 years ago

1.1.26

4 years ago

1.1.25

4 years ago

1.1.24

4 years ago

1.1.23

4 years ago

1.1.22

4 years ago

1.1.21

4 years ago

1.1.20

4 years ago

1.1.19

4 years ago

1.1.18

4 years ago

1.1.17

4 years ago

1.1.16

4 years ago

1.1.15

4 years ago

1.1.14

4 years ago

1.1.13

4 years ago

1.1.12

4 years ago

1.1.11

4 years ago

1.1.10

4 years ago

1.1.9

4 years ago

1.1.8

5 years ago

1.1.7

5 years ago

1.1.6

5 years ago

1.1.5

5 years ago

1.1.4

5 years ago

1.1.3

5 years ago

1.1.2

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago