-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
pattern.mjs
3102 lines (2837 loc) · 90.2 KB
/
pattern.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
pattern.mjs - Core pattern representation for strudel
Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/strudel/blob/main/packages/core/pattern.mjs>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import TimeSpan from './timespan.mjs';
import Fraction, { lcm } from './fraction.mjs';
import Hap from './hap.mjs';
import State from './state.mjs';
import { unionWithObj } from './value.mjs';
import {
uniqsortr,
removeUndefineds,
flatten,
id,
listRange,
curry,
_mod,
numeralArgs,
parseNumeral,
pairs,
} from './util.mjs';
import drawLine from './drawLine.mjs';
import { logger } from './logger.mjs';
let stringParser;
let __tactus = true;
export const calculateTactus = function (x) {
__tactus = x ? true : false;
};
// parser is expected to turn a string into a pattern
// if set, the reify function will parse all strings with it
// intended to use with mini to automatically interpret all strings as mini notation
export const setStringParser = (parser) => (stringParser = parser);
/** @class Class representing a pattern. */
export class Pattern {
/**
* Create a pattern. As an end user, you will most likely not create a Pattern directly.
*
* @param {function} query - The function that maps a `State` to an array of `Hap`.
* @noAutocomplete
*/
constructor(query, tactus = undefined) {
this.query = query;
this._Pattern = true; // this property is used to detectinstance of another Pattern
this.tactus = tactus; // in terms of number of steps per cycle
}
get tactus() {
return this.__tactus;
}
set tactus(tactus) {
this.__tactus = tactus === undefined ? undefined : Fraction(tactus);
}
setTactus(tactus) {
this.tactus = tactus;
return this;
}
withTactus(f) {
if (!__tactus) {
return this;
}
return new Pattern(this.query, this.tactus === undefined ? undefined : f(this.tactus));
}
get hasTactus() {
return this.tactus !== undefined;
}
//////////////////////////////////////////////////////////////////////
// Haskell-style functor, applicative and monadic operations
/**
* Returns a new pattern, with the function applied to the value of
* each hap. It has the alias `fmap`.
* @synonyms fmap
* @param {Function} func to to apply to the value
* @returns Pattern
* @example
* "0 1 2".withValue(v => v + 10).log()
*/
withValue(func) {
const result = new Pattern((state) => this.query(state).map((hap) => hap.withValue(func)));
result.tactus = this.tactus;
return result;
}
// runs func on query state
withState(func) {
return this.withHaps((haps, state) => {
func(state);
return haps;
});
}
/**
* see `withValue`
* @noAutocomplete
*/
fmap(func) {
return this.withValue(func);
}
/**
* Assumes 'this' is a pattern of functions, and given a function to
* resolve wholes, applies a given pattern of values to that
* pattern of functions.
* @param {Function} whole_func
* @param {Function} func
* @noAutocomplete
* @returns Pattern
*/
appWhole(whole_func, pat_val) {
const pat_func = this;
const query = function (state) {
const hap_funcs = pat_func.query(state);
const hap_vals = pat_val.query(state);
const apply = function (hap_func, hap_val) {
const s = hap_func.part.intersection(hap_val.part);
if (s == undefined) {
return undefined;
}
return new Hap(
whole_func(hap_func.whole, hap_val.whole),
s,
hap_func.value(hap_val.value),
hap_val.combineContext(hap_func),
);
};
return flatten(
hap_funcs.map((hap_func) => removeUndefineds(hap_vals.map((hap_val) => apply(hap_func, hap_val)))),
);
};
return new Pattern(query);
}
/**
* When this method is called on a pattern of functions, it matches its haps
* with those in the given pattern of values. A new pattern is returned, with
* each matching value applied to the corresponding function.
*
* In this `_appBoth` variant, where timespans of the function and value haps
* are not the same but do intersect, the resulting hap has a timespan of the
* intersection. This applies to both the part and the whole timespan.
* @param {Pattern} pat_val
* @noAutocomplete
* @returns Pattern
*/
appBoth(pat_val) {
const pat_func = this;
// Tidal's <*>
const whole_func = function (span_a, span_b) {
if (span_a == undefined || span_b == undefined) {
return undefined;
}
return span_a.intersection_e(span_b);
};
const result = pat_func.appWhole(whole_func, pat_val);
if (__tactus) {
result.tactus = lcm(pat_val.tactus, pat_func.tactus);
}
return result;
}
/**
* As with `appBoth`, but the `whole` timespan is not the intersection,
* but the timespan from the function of patterns that this method is called
* on. In practice, this means that the pattern structure, including onsets,
* are preserved from the pattern of functions (often referred to as the left
* hand or inner pattern).
* @param {Pattern} pat_val
* @noAutocomplete
* @returns Pattern
*/
appLeft(pat_val) {
const pat_func = this;
const query = function (state) {
const haps = [];
for (const hap_func of pat_func.query(state)) {
const hap_vals = pat_val.query(state.setSpan(hap_func.wholeOrPart()));
for (const hap_val of hap_vals) {
const new_whole = hap_func.whole;
const new_part = hap_func.part.intersection(hap_val.part);
if (new_part) {
const new_value = hap_func.value(hap_val.value);
const new_context = hap_val.combineContext(hap_func);
const hap = new Hap(new_whole, new_part, new_value, new_context);
haps.push(hap);
}
}
}
return haps;
};
const result = new Pattern(query);
result.tactus = this.tactus;
return result;
}
/**
* As with `appLeft`, but `whole` timespans are instead taken from the
* pattern of values, i.e. structure is preserved from the right hand/outer
* pattern.
* @param {Pattern} pat_val
* @noAutocomplete
* @returns Pattern
*/
appRight(pat_val) {
const pat_func = this;
const query = function (state) {
const haps = [];
for (const hap_val of pat_val.query(state)) {
const hap_funcs = pat_func.query(state.setSpan(hap_val.wholeOrPart()));
for (const hap_func of hap_funcs) {
const new_whole = hap_val.whole;
const new_part = hap_func.part.intersection(hap_val.part);
if (new_part) {
const new_value = hap_func.value(hap_val.value);
const new_context = hap_val.combineContext(hap_func);
const hap = new Hap(new_whole, new_part, new_value, new_context);
haps.push(hap);
}
}
}
return haps;
};
const result = new Pattern(query);
result.tactus = pat_val.tactus;
return result;
}
bindWhole(choose_whole, func) {
const pat_val = this;
const query = function (state) {
const withWhole = function (a, b) {
return new Hap(
choose_whole(a.whole, b.whole),
b.part,
b.value,
Object.assign({}, a.context, b.context, {
locations: (a.context.locations || []).concat(b.context.locations || []),
}),
);
};
const match = function (a) {
return func(a.value)
.query(state.setSpan(a.part))
.map((b) => withWhole(a, b));
};
return flatten(pat_val.query(state).map((a) => match(a)));
};
return new Pattern(query);
}
bind(func) {
const whole_func = function (a, b) {
if (a == undefined || b == undefined) {
return undefined;
}
return a.intersection_e(b);
};
return this.bindWhole(whole_func, func);
}
join() {
// Flattens a pattern of patterns into a pattern, where wholes are
// the intersection of matched inner and outer haps.
return this.bind(id);
}
outerBind(func) {
return this.bindWhole((a) => a, func).setTactus(this.tactus);
}
outerJoin() {
// Flattens a pattern of patterns into a pattern, where wholes are
// taken from outer haps.
return this.outerBind(id);
}
innerBind(func) {
return this.bindWhole((_, b) => b, func);
}
innerJoin() {
// Flattens a pattern of patterns into a pattern, where wholes are
// taken from inner haps.
return this.innerBind(id);
}
// Flatterns patterns of patterns, by retriggering/resetting inner patterns at onsets of outer pattern haps
resetJoin(restart = false) {
const pat_of_pats = this;
return new Pattern((state) => {
return (
pat_of_pats
// drop continuous haps from the outer pattern.
.discreteOnly()
.query(state)
.map((outer_hap) => {
return (
outer_hap.value
// reset = align the inner pattern cycle start to outer pattern haps
// restart = align the inner pattern cycle zero to outer pattern haps
.late(restart ? outer_hap.whole.begin : outer_hap.whole.begin.cyclePos())
.query(state)
.map((inner_hap) =>
new Hap(
// Supports continuous haps in the inner pattern
inner_hap.whole ? inner_hap.whole.intersection(outer_hap.whole) : undefined,
inner_hap.part.intersection(outer_hap.part),
inner_hap.value,
).setContext(outer_hap.combineContext(inner_hap)),
)
// Drop haps that didn't intersect
.filter((hap) => hap.part)
);
})
.flat()
);
});
}
restartJoin() {
return this.resetJoin(true);
}
// Like the other joins above, joins a pattern of patterns of values, into a flatter
// pattern of values. In this case it takes whole cycles of the inner pattern to fit each event
// in the outer pattern.
squeezeJoin() {
// A pattern of patterns, which we call the 'outer' pattern, with patterns
// as values which we call the 'inner' patterns.
const pat_of_pats = this;
function query(state) {
// Get the events with the inner patterns. Ignore continuous events (without 'wholes')
const haps = pat_of_pats.discreteOnly().query(state);
// A function to map over the events from the outer pattern.
function flatHap(outerHap) {
// Get the inner pattern, slowed and shifted so that the 'whole'
// timespan of the outer event corresponds to the first cycle of the
// inner event
const inner_pat = outerHap.value._focusSpan(outerHap.wholeOrPart());
// Get the inner events, from the timespan of the outer event's part
const innerHaps = inner_pat.query(state.setSpan(outerHap.part));
// A function to map over the inner events, to combine them with the
// outer event
function munge(outer, inner) {
let whole = undefined;
if (inner.whole && outer.whole) {
whole = inner.whole.intersection(outer.whole);
if (!whole) {
// The wholes are present, but don't intersect
return undefined;
}
}
const part = inner.part.intersection(outer.part);
if (!part) {
// The parts don't intersect
return undefined;
}
const context = inner.combineContext(outer);
return new Hap(whole, part, inner.value, context);
}
return innerHaps.map((innerHap) => munge(outerHap, innerHap));
}
const result = flatten(haps.map(flatHap));
// remove undefineds
return result.filter((x) => x);
}
return new Pattern(query);
}
squeezeBind(func) {
return this.fmap(func).squeezeJoin();
}
polyJoin = function () {
const pp = this;
return pp.fmap((p) => p.s_extend(pp.tactus.div(p.tactus))).outerJoin();
};
polyBind(func) {
return this.fmap(func).polyJoin();
}
//////////////////////////////////////////////////////////////////////
// Utility methods mainly for internal use
/**
* Query haps inside the given time span.
*
* @param {Fraction | number} begin from time
* @param {Fraction | number} end to time
* @returns Hap[]
* @example
* const pattern = sequence('a', ['b', 'c'])
* const haps = pattern.queryArc(0, 1)
* console.log(haps)
* silence
* @noAutocomplete
*/
queryArc(begin, end, controls = {}) {
try {
return this.query(new State(new TimeSpan(begin, end), controls));
} catch (err) {
logger(`[query]: ${err.message}`, 'error');
return [];
}
}
/**
* Returns a new pattern, with queries split at cycle boundaries. This makes
* some calculations easier to express, as all haps are then constrained to
* happen within a cycle.
* @returns Pattern
* @noAutocomplete
*/
splitQueries() {
const pat = this;
const q = (state) => {
return flatten(state.span.spanCycles.map((subspan) => pat.query(state.setSpan(subspan))));
};
return new Pattern(q);
}
/**
* Returns a new pattern, where the given function is applied to the query
* timespan before passing it to the original pattern.
* @param {Function} func the function to apply
* @returns Pattern
* @noAutocomplete
*/
withQuerySpan(func) {
return new Pattern((state) => this.query(state.withSpan(func)));
}
withQuerySpanMaybe(func) {
const pat = this;
return new Pattern((state) => {
const newState = state.withSpan(func);
if (!newState.span) {
return [];
}
return pat.query(newState);
});
}
/**
* As with `withQuerySpan`, but the function is applied to both the
* begin and end time of the query timespan.
* @param {Function} func the function to apply
* @returns Pattern
* @noAutocomplete
*/
withQueryTime(func) {
return new Pattern((state) => this.query(state.withSpan((span) => span.withTime(func))));
}
/**
* Similar to `withQuerySpan`, but the function is applied to the timespans
* of all haps returned by pattern queries (both `part` timespans, and where
* present, `whole` timespans).
* @param {Function} func
* @returns Pattern
* @noAutocomplete
*/
withHapSpan(func) {
return new Pattern((state) => this.query(state).map((hap) => hap.withSpan(func)));
}
/**
* As with `withHapSpan`, but the function is applied to both the
* begin and end time of the hap timespans.
* @param {Function} func the function to apply
* @returns Pattern
* @noAutocomplete
*/
withHapTime(func) {
return this.withHapSpan((span) => span.withTime(func));
}
/**
* Returns a new pattern with the given function applied to the list of haps returned by every query.
* @param {Function} func
* @returns Pattern
* @noAutocomplete
*/
withHaps(func) {
const result = new Pattern((state) => func(this.query(state), state));
result.tactus = this.tactus;
return result;
}
/**
* As with `withHaps`, but applies the function to every hap, rather than every list of haps.
* @param {Function} func
* @returns Pattern
* @noAutocomplete
*/
withHap(func) {
return this.withHaps((haps) => haps.map(func));
}
/**
* Returns a new pattern with the context field set to every hap set to the given value.
* @param {*} context
* @returns Pattern
* @noAutocomplete
*/
setContext(context) {
return this.withHap((hap) => hap.setContext(context));
}
/**
* Returns a new pattern with the given function applied to the context field of every hap.
* @param {Function} func
* @returns Pattern
* @noAutocomplete
*/
withContext(func) {
const result = this.withHap((hap) => hap.setContext(func(hap.context)));
if (this.__pure !== undefined) {
result.__pure = this.__pure;
result.__pure_loc = this.__pure_loc;
}
return result;
}
/**
* Returns a new pattern with the context field of every hap set to an empty object.
* @returns Pattern
* @noAutocomplete
*/
stripContext() {
return this.withHap((hap) => hap.setContext({}));
}
/**
* Returns a new pattern with the given location information added to the
* context of every hap.
* @param {Number} start start offset
* @param {Number} end end offset
* @returns Pattern
* @noAutocomplete
*/
withLoc(start, end) {
const location = {
start,
end,
};
const result = this.withContext((context) => {
const locations = (context.locations || []).concat([location]);
return { ...context, locations };
});
if (this.__pure) {
result.__pure = this.__pure;
result.__pure_loc = location;
}
return result;
}
/**
* Returns a new Pattern, which only returns haps that meet the given test.
* @param {Function} hap_test - a function which returns false for haps to be removed from the pattern
* @returns Pattern
* @noAutocomplete
*/
filterHaps(hap_test) {
return new Pattern((state) => this.query(state).filter(hap_test));
}
/**
* As with `filterHaps`, but the function is applied to values
* inside haps.
* @param {Function} value_test
* @returns Pattern
* @noAutocomplete
*/
filterValues(value_test) {
return new Pattern((state) => this.query(state).filter((hap) => value_test(hap.value))).setTactus(this.tactus);
}
/**
* Returns a new pattern, with haps containing undefined values removed from
* query results.
* @returns Pattern
* @noAutocomplete
*/
removeUndefineds() {
return this.filterValues((val) => val != undefined);
}
/**
* Returns a new pattern, with all haps without onsets filtered out. A hap
* with an onset is one with a `whole` timespan that begins at the same time
* as its `part` timespan.
* @returns Pattern
* @noAutocomplete
*/
onsetsOnly() {
// Returns a new pattern that will only return haps where the start
// of the 'whole' timespan matches the start of the 'part'
// timespan, i.e. the haps that include their 'onset'.
return this.filterHaps((hap) => hap.hasOnset());
}
/**
* Returns a new pattern, with 'continuous' haps (those without 'whole'
* timespans) removed from query results.
* @returns Pattern
* @noAutocomplete
*/
discreteOnly() {
// removes continuous haps that don't have a 'whole' timespan
return this.filterHaps((hap) => hap.whole);
}
/**
* Combines adjacent haps with the same value and whole. Only
* intended for use in tests.
* @noAutocomplete
*/
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.
* @param {Boolean} with_context - set to true, otherwise the context field
* will be stripped from the resulting haps.
* @returns [Hap]
* @noAutocomplete
*/
firstCycle(with_context = false) {
var self = this;
if (!with_context) {
self = self.stripContext();
}
return self.query(new State(new TimeSpan(Fraction(0), Fraction(1))));
}
/**
* Accessor for a list of values returned by querying the first cycle.
* @noAutocomplete
*/
get firstCycleValues() {
return this.firstCycle().map((hap) => hap.value);
}
/**
* More human-readable version of the `firstCycleValues` accessor.
* @noAutocomplete
*/
get showFirstCycle() {
return this.firstCycle().map(
(hap) => `${hap.value}: ${hap.whole.begin.toFraction()} - ${hap.whole.end.toFraction()}`,
);
}
/**
* Returns a new pattern, which returns haps sorted in temporal order. Mainly
* of use when comparing two patterns for equality, in tests.
* @returns Pattern
* @noAutocomplete
*/
sortHapsByPart() {
return this.withHaps((haps) =>
haps.sort((a, b) =>
a.part.begin
.sub(b.part.begin)
.or(a.part.end.sub(b.part.end))
.or(a.whole.begin.sub(b.whole.begin).or(a.whole.end.sub(b.whole.end))),
),
);
}
asNumber() {
return this.fmap(parseNumeral);
}
//////////////////////////////////////////////////////////////////////
// Operators - see 'make composers' later..
_opIn(other, func) {
return this.fmap(func).appLeft(reify(other));
}
_opOut(other, func) {
return this.fmap(func).appRight(reify(other));
}
_opMix(other, func) {
return this.fmap(func).appBoth(reify(other));
}
_opSqueeze(other, func) {
const otherPat = reify(other);
return this.fmap((a) => otherPat.fmap((b) => func(a)(b))).squeezeJoin();
}
_opSqueezeOut(other, func) {
const thisPat = this;
const otherPat = reify(other);
return otherPat.fmap((a) => thisPat.fmap((b) => func(b)(a))).squeezeJoin();
}
_opReset(other, func) {
const otherPat = reify(other);
return otherPat.fmap((b) => this.fmap((a) => func(a)(b))).resetJoin();
}
_opRestart(other, func) {
const otherPat = reify(other);
return otherPat.fmap((b) => this.fmap((a) => func(a)(b))).restartJoin();
}
_opPoly(other, func) {
const otherPat = reify(other);
return this.fmap((b) => otherPat.fmap((a) => func(a)(b))).polyJoin();
}
//////////////////////////////////////////////////////////////////////
// End-user methods.
// Those beginning with an underscore (_) are 'patternified',
// i.e. versions are created without the underscore, that are
// magically transformed to accept patterns for all their arguments.
//////////////////////////////////////////////////////////////////////
// Methods without corresponding toplevel functions
/**
* Layers the result of the given function(s). Like `superimpose`, but without the original pattern:
* @name layer
* @memberof Pattern
* @synonyms apply
* @returns Pattern
* @example
* "<0 2 4 6 ~ 4 ~ 2 0!3 ~!5>*8"
* .layer(x=>x.add("0,2"))
* .scale('C minor').note()
*/
layer(...funcs) {
return stack(...funcs.map((func) => func(this)));
}
/**
* Superimposes the result of the given function(s) on top of the original pattern:
* @name superimpose
* @memberof Pattern
* @returns Pattern
* @example
* "<0 2 4 6 ~ 4 ~ 2 0!3 ~!5>*8"
* .superimpose(x=>x.add(2))
* .scale('C minor').note()
*/
superimpose(...funcs) {
return this.stack(...funcs.map((func) => func(this)));
}
//////////////////////////////////////////////////////////////////////
// Multi-pattern functions
stack(...pats) {
return stack(this, ...pats);
}
sequence(...pats) {
return sequence(this, ...pats);
}
seq(...pats) {
return sequence(this, ...pats);
}
cat(...pats) {
return cat(this, ...pats);
}
fastcat(...pats) {
return fastcat(this, ...pats);
}
slowcat(...pats) {
return slowcat(this, ...pats);
}
//////////////////////////////////////////////////////////////////////
// Context methods - ones that deal with metadata
onTrigger(onTrigger, dominant = true) {
return this.withHap((hap) =>
hap.setContext({
...hap.context,
onTrigger: (...args) => {
// run previously set trigger, if it exists
hap.context.onTrigger?.(...args);
onTrigger(...args);
},
// if dominantTrigger is set to true, the default output (webaudio) will be disabled
// when using multiple triggers, you cannot flip this flag to false again!
// example: x.csound('CooLSynth').log() as well as x.log().csound('CooLSynth') should work the same
dominantTrigger: hap.context.dominantTrigger || dominant,
}),
);
}
log(func = (_, hap) => `[hap] ${hap.showWhole(true)}`, getData = (_, hap) => ({ hap })) {
return this.onTrigger((...args) => {
logger(func(...args), undefined, getData(...args));
}, false);
}
logValues(func = id) {
return this.log((_, hap) => func(hap.value));
}
//////////////////////////////////////////////////////////////////////
// Visualisation
drawLine() {
console.log(drawLine(this));
return this;
}
}
//////////////////////////////////////////////////////////////////////
// functions relating to chords/patterns of lists/lists of patterns
// returns Array<Hap[]> where each list of haps satisfies eq
function groupHapsBy(eq, haps) {
let groups = [];
haps.forEach((hap) => {
const match = groups.findIndex(([other]) => eq(hap, other));
if (match === -1) {
groups.push([hap]);
} else {
groups[match].push(hap);
}
});
return groups;
}
// congruent haps = haps with equal spans
const congruent = (a, b) => a.spanEquals(b);
// Pattern<Hap<T>> -> Pattern<Hap<T[]>>
// returned pattern contains arrays of congruent haps
Pattern.prototype.collect = function () {
return this.withHaps((haps) =>
groupHapsBy(congruent, haps).map((_haps) => new Hap(_haps[0].whole, _haps[0].part, _haps, {})),
);
};
/**
* Selects indices in in stacked notes.
* @example
* note("<[c,eb,g]!2 [c,f,ab] [d,f,ab]>")
* .arpWith(haps => haps[2])
* */
Pattern.prototype.arpWith = function (func) {
return this.collect()
.fmap((v) => reify(func(v)))
.innerJoin()
.withHap((h) => new Hap(h.whole, h.part, h.value.value, h.combineContext(h.value)));
};
/**
* Selects indices in in stacked notes.
* @example
* note("<[c,eb,g]!2 [c,f,ab] [d,f,ab]>")
* .arp("0 [0,2] 1 [0,2]")
* */
Pattern.prototype.arp = function (pat) {
return this.arpWith((haps) => pat.fmap((i) => haps[i % haps.length]));
};
/*
* Takes a time duration followed by one or more patterns, and shifts the given patterns in time, so they are
* distributed equally over the given time duration. They are then combined with the pattern 'weave' is called on, after it has been stretched out (i.e. slowed down by) the time duration.
* @name weave
* @memberof Pattern
* @example pan(saw).weave(4, s("bd(3,8)"), s("~ sd"))
* @example n("0 1 2 3 4 5 6 7").weave(8, s("bd(3,8)"), s("~ sd"))
addToPrototype('weave', function (t, ...pats) {
return this.weaveWith(t, ...pats.map((x) => set.out(x)));
});
*/
/*
* Like 'weave', but accepts functions rather than patterns, which are applied to the pattern.
* @name weaveWith
* @memberof Pattern
addToPrototype('weaveWith', function (t, ...funcs) {
const pat = this;
const l = funcs.length;
t = Fraction(t);
if (l == 0) {
return silence;
}
return stack(...funcs.map((func, i) => pat.inside(t, func).early(Fraction(i).div(l))))._slow(t);
});
*/
//////////////////////////////////////////////////////////////////////
// compose matrix functions
function _nonArrayObject(x) {
return !Array.isArray(x) && typeof x === 'object';
}
function _composeOp(a, b, func) {
if (_nonArrayObject(a) || _nonArrayObject(b)) {
if (!_nonArrayObject(a)) {
a = { value: a };
}
if (!_nonArrayObject(b)) {
b = { value: b };
}
return unionWithObj(a, b, func);
}
return func(a, b);
}
// Make composers
(function () {
// pattern composers
const composers = {
set: [(a, b) => b],
keep: [(a) => a],
keepif: [(a, b) => (b ? a : undefined)],
// numerical functions
/**
*
* Assumes a pattern of numbers. Adds the given number to each item in the pattern.
* @name add
* @memberof Pattern
* @example
* // Here, the triad 0, 2, 4 is shifted by different amounts
* n("0 2 4".add("<0 3 4 0>")).scale("C:major")
* // Without add, the equivalent would be:
* // n("<[0 2 4] [3 5 7] [4 6 8] [0 2 4]>").scale("C:major")
* @example
* // You can also use add with notes:
* note("c3 e3 g3".add("<0 5 7 0>"))
* // Behind the scenes, the notes are converted to midi numbers:
* // note("48 52 55".add("<0 5 7 0>"))
*/
add: [numeralArgs((a, b) => a + b)], // support string concatenation
/**
*
* Like add, but the given numbers are subtracted.