diff --git a/packages/core/signal.mjs b/packages/core/signal.mjs index 8340bc9f..6c905b55 100644 --- a/packages/core/signal.mjs +++ b/packages/core/signal.mjs @@ -160,16 +160,19 @@ const timeToRands = (t, n) => timeToRandsPrime(timeToIntSeed(t), n); export const run = (n) => saw.range(0, n).floor().segment(n); /** - * A discrete binary pattern using a decimal/hex number as input + * @name binaryN + * Creates a discrete pattern using binary representation. + * @param {number} n - input number to convert to binary + * @param {number} nBits - pattern length, defaults to 16 * @example - * "hh".s().struct(binary(55532)) + * "hh".s().struct(binaryN(55532, 16)) * // "hh".s().struct("1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0") */ -export const binary = (n) => { - const binLen = 16; - // Shift right and mask, with msb at the end/right-side - const i = run(binLen).mul(-1).add(binLen - 1) - return reify(n).segment(binLen).brshift(i).band(pure(1)); +export const binaryN = (n, nBits = 16) => { + nBits = reify(nBits); + // Shift and mask, putting msb on the right-side + const i = run(nBits).mul(-1).add(nBits.sub(1)); + return reify(n).segment(nBits).brshift(i).band(pure(1)); }; export const randrun = (n) => { diff --git a/packages/core/test/pattern.test.mjs b/packages/core/test/pattern.test.mjs index 03f2c60f..7e6d8fd8 100644 --- a/packages/core/test/pattern.test.mjs +++ b/packages/core/test/pattern.test.mjs @@ -46,7 +46,7 @@ import { rev, time, run, - binary, + binaryN, pick, stackLeft, stackRight, @@ -959,15 +959,15 @@ describe('Pattern', () => { expect(run(4).firstCycle()).toStrictEqual(sequence(0, 1, 2, 3).firstCycle()); }); }); - describe('binary', () => { + describe('binaryN', () => { it('Can make a binary pattern from a decimal', () => { - expect(binary(55532).firstCycle()).toStrictEqual( + expect(binaryN(55532).firstCycle()).toStrictEqual( sequence(1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0).firstCycle(), ); }); - it('Can make a binary pattern from a numerical pattern', () => { - expect(binary(pure(0x1337)).firstCycle()).toStrictEqual( - sequence(0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1).firstCycle(), + it('Can make a binary pattern from patterned inputs', () => { + expect(binaryN(pure(0x1337), pure(14)).firstCycle()).toStrictEqual( + sequence(0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1).firstCycle(), ); }); }); diff --git a/test/__snapshots__/examples.test.mjs.snap b/test/__snapshots__/examples.test.mjs.snap index fd7169c5..6dce5739 100644 --- a/test/__snapshots__/examples.test.mjs.snap +++ b/test/__snapshots__/examples.test.mjs.snap @@ -967,7 +967,8 @@ exports[`runs examples > example "begin" example index 0 1`] = ` ] `; -exports[`runs examples > example "binary" example index 0 1`] = ` +exports[`runs examples > example "binaryN +Creates a discrete pattern using binary representation." example index 0 1`] = ` [ "[ 0/1 → 1/16 | s:hh ]", "[ 1/16 → 1/8 | s:hh ]",