Pick random lines from a text document
Split text into lines and return count of them in random order.
function randomLines(text, count) {
const lines = text.split(/\r?\n/);
for (let i = lines.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[lines[i], lines[j]] = [lines[j], lines[i]];
}
return lines.slice(0, count);
}
Usage
const poem = `one
two
three
four
five`;
randomLines(poem, 4).length; // → 4
new Set(randomLines(poem, 5)).size; // → 5
Know the limits
- The original had the same reduce-and-splice flaw as Get random items of an array: requesting more than half the lines returned fewer.
- Lines split on LF and CRLF. A trailing newline adds one empty line, which can be drawn.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Pick random lines from a text document from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Shuffles the lines and slices; the original returned fewer lines than requested when asked for more than half. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Generate a random boolean — Return true or false with equal probability.
- Generate a random floating point number in given range — Scale Math.random into [min, max).
- Generate a random hex color — Return a #rrggbb color from 24 random bits.