Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Tone/event/PatternGenerator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
]);
});
});
});
21 changes: 12 additions & 9 deletions Tone/event/PatternGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,15 +138,18 @@ function* randomWalk(numValues: number): IterableIterator<number> {
// 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;
}
Expand Down