Skip to content

random-array-element 1.2.3

Install from the command line:
Learn more about npm packages
$ npm install @smakss/random-array-element@1.2.3
Install via package.json:
"@smakss/random-array-element": "1.2.3"

About this version

Random array element without repetition

npm Snyk Vulnerabilities for npm package NPM npm npm bundle size (scoped)

In order to select an element within an array, you can simply use Math.random() but what about when you don't want to select an element that selected before. Here this package will come to use. This package works with simple closure, so you can simply invoke randomArrayElement once everywhere in your project then use it to generate random elements from your array no matter your array is flat or nested, it will choose a random unique element from your array until all the array element get exhausted.

How it works?

To install it you can simply do the following command:

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

to include it with common js module you should do this:

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

and to include it with ECMAscript module you can simply do this one:

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

then to use it within your application you can do it just like this:

const chooser = randomArrayElement();

// Result: -1
// If the input was not array or was empty the chooser will be equal to -1, so chooser() will throw an error.
const chooser = randomArrayElement(['Foo', 'Bar', 'FU', 'FooBar']);
// Initiating the selector once and then we can use the returned function to select random none repeatable elements from the array.

chooser();
// Result: Foo

chooser();
// Result: Bar

chooser();
// Result: FU

chooser();
// Result: FooBar

chooser();
// Result: Foo
// It will only repeats, once all items within the array are exhausted.

Demo

You can check the working demo in runkit.

Details


Assets

  • random-array-element-1.2.3-npm.tgz

Download activity

  • Total downloads 0
  • Last 30 days 0
  • Last week 0
  • Today 0