Skip to content

Commit

Permalink
Give special treatment to the last interval in keepUnique
Browse files Browse the repository at this point in the history
ref #341
  • Loading branch information
frostburn committed Jun 13, 2024
1 parent 3c6c79c commit 380779d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/parser/__tests__/expression.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2133,6 +2133,11 @@ describe('SonicWeave expression evaluator', () => {
const {fraction} = parseSingle('2 -1');
expect(fraction).toBe('1');
});

it('keeps unique strings', () => {
const strings = evaluate('keepUnique(["hello", "world", "hello"])');
expect(strings).toEqual(['hello', 'world']);
});
});

describe('Poor grammar / Fun with "<"', () => {
Expand Down Expand Up @@ -2170,6 +2175,7 @@ describe('Poor grammar / Fun with "<"', () => {
expect(fraction).toBe('9');
});

// TODO: Move under the correct heading.
it('multiplies a monzo from the left', () => {
const {fraction} = parseSingle('2 [2 -1>');
expect(fraction).toBe('16/9');
Expand Down
5 changes: 5 additions & 0 deletions src/parser/__tests__/stdlib.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1594,4 +1594,9 @@ describe('SonicWeave standard library', () => {
'2/1',
]);
});

it('preserves equave formatting in organize()', () => {
const scale = expand('1;2/1;organize()');
expect(scale).toEqual(['2/1']);
});
});
12 changes: 12 additions & 0 deletions src/stdlib/builtin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1947,7 +1947,16 @@ function keepUnique(this: ExpressionVisitor, scale?: SonicWeaveValue) {
if (!Array.isArray(scale)) {
throw new Error('An array is required.');
}
if (!scale.length) {
return [];
}
const seen = new Set();
const equave = scale.pop()!;
if (equave instanceof Interval) {
seen.add(equave.valueOf());
} else {
scale.push(equave);
}
const result: SonicWeavePrimitive[] = [];
for (const interval of scale) {
const value = interval ? interval.valueOf() : interval;
Expand All @@ -1957,6 +1966,9 @@ function keepUnique(this: ExpressionVisitor, scale?: SonicWeaveValue) {
result.push(interval);
seen.add(value);
}
if (equave instanceof Interval) {
result.push(equave);
}
return result;
}
keepUnique.__doc__ =
Expand Down

0 comments on commit 380779d

Please sign in to comment.