Skip to content

Commit

Permalink
.defragmentHaps() (#299)
Browse files Browse the repository at this point in the history
  • Loading branch information
yaxu committed Dec 11, 2022
1 parent c5083b2 commit 56424d2
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
52 changes: 52 additions & 0 deletions packages/core/pattern.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,58 @@ export class Pattern {
return this.filterHaps((hap) => hap.whole);
}

/**
* Combines adjacent haps with the same value and whole. Only
* intended for use in tests.
*/
defragmentHaps() {
// remove continuous haps
const pat = this.discreteOnly();

return pat.withHaps((haps) => {
const result = [];
for (var i=0; i < haps.length; ++i) {
var searching = true;
var a = haps[i];
while (searching) {
const a_value = JSON.stringify(haps[i].value);
var found = false;

for(var j=i+1; j<haps.length; j++) {
const b = haps[j];

if (a.whole.equals(b.whole)) {
if (a.part.begin.eq(b.part.end)) {
if (a_value === JSON.stringify(b.value)) {
// eat the matching hap into 'a'
a = new Hap(a.whole, new TimeSpan(b.part.begin, a.part.end), a.value)
haps.splice(j,1);
// restart the search
found = true;
break;
}
}
else if (b.part.begin.eq(a.part.end)) {
if (a_value == JSON.stringify(b.value)) {
// eat the matching hap into 'a'
a = new Hap(a.whole, new TimeSpan(a.part.begin, b.part.end), a.value)
haps.splice(j,1);
// restart the search
found = true;
break;
}
}
}
}

searching = found;
}
result.push(a);
}
return result;
});
}

/**
* Queries the pattern for the first cycle, returning Haps. Mainly of use when
* debugging a pattern.
Expand Down
18 changes: 18 additions & 0 deletions packages/core/test/pattern.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -915,4 +915,22 @@ describe('Pattern', () => {
expect(sequence(1, 2).add.squeeze(4, 5).firstCycle()).toStrictEqual(sequence(5, 6, 6, 7).firstCycle());
});
});
describe('defragmentHaps', () => {
it('Can merge two touching haps with same whole and value', () => {
expect(stack(pure('a').mask(1,0), pure('a').mask(0,1)).defragmentHaps().firstCycle().length)
.toStrictEqual(1);
});
it('Doesnt merge two overlapping haps', () => {
expect(stack(pure('a').mask(1,1,0), pure('a').mask(0,1)).defragmentHaps().firstCycle().length)
.toStrictEqual(2);
});
it('Doesnt merge two touching haps with different values', () => {
expect(stack(pure('a').mask(1,0), pure('b').mask(0,1)).defragmentHaps().firstCycle().length)
.toStrictEqual(2);
});
it('Doesnt merge two touching haps with different wholes', () => {
expect(stack(sequence('a', silence), pure('a').mask(0,1)).defragmentHaps().firstCycle().length)
.toStrictEqual(2);
});
});
});

0 comments on commit 56424d2

Please sign in to comment.