Skip to content

Commit 5b1094e

Browse files
RobertJohnDavidsonRobert Davidson
andauthored
Add bounds check to pickRandom nbItems (#128)
Co-authored-by: Robert Davidson <[email protected]>
1 parent 074fcae commit 5b1094e

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/methods/selecting/pickRandomItems.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ export default function pickRandomItems(
1010
seed?: number,
1111
verbose = false
1212
): SimpleDataItem[] {
13+
if (nbItems <= 0) {
14+
throw new Error("You must choose a number of items greater than 0")
15+
}
16+
if (nbItems > data.length) {
17+
nbItems = data.length
18+
}
19+
1320
const shuffle = seed ? shuffler(randomLcg(seed)) : shuffler(randomLcg())
1421
const randomizedData = shuffle(data).slice(0, nbItems)
1522
const nbRemoved = data.length - nbItems

test/unit/methods/selecting/pickRandomItems.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,15 @@ describe("pickRandomItems", function () {
2727
])
2828
})
2929
})
30+
31+
describe("pickRandomItems", function () {
32+
it("should return an error because a negative value is given", function () {
33+
const data = [
34+
{ key1: 0, key2: 2 },
35+
{ key1: 1, key2: 2 },
36+
{ key1: 2, key2: 4 },
37+
{ key1: 2, key2: 6 },
38+
]
39+
assert.throws(() => pickRandomItems(data, -1), Error)
40+
})
41+
})

0 commit comments

Comments
 (0)