Strudel, how to do a progressive fade out

I started experimenting with strudel less than a month ago (I'm a beginner), but I haven't seen any examples of how to do a fade-out to smoothly end a track.

For now, the most "elegant" solution I've come up with is the following:

all(x => x.when(
   time.gt(5),
   y => y.postgain("<1!6 0.75 0.50 0.25 0.1 0!1000>")
))

If we want to fade-out after cycle N, we have to use

all(x => x.when(
   time.gt(N),
   y => y.postgain("<1!(N+1) 0.75 0.50 0.25 0.1 0!1000>")
))

We use postgain, instead of gain, so that tracks with a defined gain don't jump to gain(1) when the fade-out starts, but rather remain relative to their current volume.

If you can think of a simpler way, please let me know.

A few things:

You can use the filterWhen function to enable/disable a track based on the global time.

You can use mul to multiply the existing gain/postgain values instead of setting them, preserving any previously set values on the pattern.

Combining this, we can easily create fadeOut and fadeIn functions:

register('fadeIn', (start, end, pat) => stack(
  pat.filterWhen(t => t >= start && t < end).mul(postgain(saw.slow(end - start).late(start))),
  pat.filterWhen(t => t >= end),
))

register('fadeOut', (start, end, pat) => stack(
  pat.filterWhen(t => t < start),
  pat.filterWhen(t => t >= start && t < end).mul(postgain(isaw.slow(end - start).late(start)))
))

As you can see we simply create a stack that has 2 patterns: 1 that plays normally when that pattern is supposed to play, and another that modulates the postgain from 0 to 1 or 1 to 0 over the correct number of cycles.

Because we're using mul to apply the postgain, you can use this anywhere without breaking existing volume controls on the rest of the patterns.

As I mentioned, I'm a complete novice with Strudel. Thanks for your comment; your approach is definitely much more elegant (and allows it to be applied to individual tracks).

I was unaware of the existence of .filterWhen(), .isaw, and .late().

You've also just solved another question I had (how to generate progressive values linearly).

Thanks for taking the time to reply.