Languages
[Edit]
EN

JavaScript - random element from stream of elements

9 points
Created by:
Giles-Whittaker
739

In this short article, we would like to show how using JavaScript, get a random element from the stream when we don't know the number of stream elements.

Condition used to decide if the stream element should be treat as a potential randomization result is:

Condition used to select potential random stream element using JavaScript.
Condition used to select potential random stream element using JavaScript.

Practical example:

// ONLINE-RUNNER:browser;

const randomizeElemnt = stream => {
    let result = null;
    for (let i = 1; true; ++i) {
        const element = stream.next();
  		if (element == null) { // null or undefined
        	break;
        }
        const number = Math.random();
        if (number * i < 1.0) {
            result = element;
        }
    }
	return result;
};


// Usage example:

const createStream = count => {
  	let index = -1;
    return {
        next: () => {
            index += 1;
            return index < count ? index : null;
        }
    };
};

const stream = createStream(10); // 10 elements, next() returns next element or null
const element = randomizeElemnt(stream);

console.log(element);

 

Alternative titles

  1. JavaScript - random element from sequence of elements
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join