diff --git a/Tone/event/PatternGenerator.test.ts b/Tone/event/PatternGenerator.test.ts index 7a19746c3..6ec538308 100644 --- a/Tone/event/PatternGenerator.test.ts +++ b/Tone/event/PatternGenerator.test.ts @@ -99,5 +99,23 @@ describe("PatternGenerator", () => { currentIndex = nextIndex; } }); + + it("never randomly walks outside of the range of values", () => { + [1, 2, 3, 4].forEach((numValues) => { + const pattern = PatternGenerator(numValues, "randomWalk"); + for (let i = 0; i < 100; i++) { + expect(pattern.next().value) + .to.be.at.least(0) + .and.at.most(numValues - 1); + } + }); + }); + + it("randomly walks in place when there is only one value", () => { + const pattern = PatternGenerator(1, "randomWalk"); + expect(getArrayValues(pattern, 10)).to.deep.equal([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]); + }); }); }); diff --git a/Tone/event/PatternGenerator.ts b/Tone/event/PatternGenerator.ts index 7b4679662..aebfe611b 100644 --- a/Tone/event/PatternGenerator.ts +++ b/Tone/event/PatternGenerator.ts @@ -138,15 +138,18 @@ function* randomWalk(numValues: number): IterableIterator { // randomly choose a starting index let index = Math.floor(Math.random() * numValues); while (true) { - if (index === 0) { - index++; // at bottom, so force upward step - } else if (index === numValues - 1) { - index--; // at top, so force downward step - } else if (Math.random() < 0.5) { - // else choose random downward or upward step - index--; - } else { - index++; + // with a single value there is nowhere to step to + if (numValues > 1) { + if (index === 0) { + index++; // at bottom, so force upward step + } else if (index === numValues - 1) { + index--; // at top, so force downward step + } else if (Math.random() < 0.5) { + // else choose random downward or upward step + index--; + } else { + index++; + } } yield index; }