I came across this JS code snippet:
function append(demo = "", file = "") {
const extra = "ctl=1&embed=1";
if (demo && file) return `/${demo}/?file=${file}&${extra}`;
if (!demo && file) return `/?file=${file}&${extra}`;
if (demo && !file) return `/${demo}&${extra}`;
return `?${extra}`;
}
I can port this easily to Raku using if
s but I thought using given
/when
would be a nice way of showcasing that feature. I came up with the following:
sub append(Str :$demo, Str :$file) {
my $extra = "ctl=1&embed=1";
given ($demo, $file) {
when $demo.so, $file.so { "/$demo/?file=$file&$extra" }
when $demo.not, $file.so { "/?file=$file&$extra" }
when $demo.so, $file.not { "/$demo?$extra" }
default { "?$extra" }
}
}
say append :file("here"), :demo("there"); # /there/?file=here&ctl=1&embed=1
say append :file("here"); # /?file=here&ctl=1&embed=1
say append :demo("here"); # /here?ctl=1&embed=1
say append; # ?ctl=1&embed=1
However it's quite repetitive and I'm not even sure if it's idiomatic Raku so I figured I could do the following:
sub append(Str :$demo = '', Str :$file = '') {
my $extra = "ctl=1&embed=1";
given ($demo.so, $file.so) {
when (True, True) { "/$demo/?file=$file&$extra" }
when (False, True) { "/?file=$file&$extra" }
when (True, False) { "/$demo?$extra" }
default { "?$extra" }
}
}
This doesn't work as expected though. Thus, is it even possible to bind a list of values to the topic variable $_
and smartmatch against it with when
s? I (mis)remember Daniel "codesections" Sockwell doing something to this extent but I cannot remember where.