Random template-string hacks
This function riffles two strings (i.e. turns "abc","de"
into "adbec"
):
f=(x,y)=>String.raw({raw:x},...y)
Note that this only works when x
is longer than y
. How does it work, you ask? String.raw
is designed to be a template tag, like so:
String.raw`x: ${x}\ny: ${y}\nx + y: ${x + y}`
This basically calls String.raw(["x: ", "\ny: ", "\nx + y: ", ""], x, y, x + y)
, though it's not that simple. The template array also has a special raw
property, which is basically a copy of the array, but with the raw strings. String.raw(x, ...args)
basically returns x.raw[0] + args[0] + x.raw[1] + args[1] + x.raw[2] + ...
and so on until x
runs out of items.
So now that we know how String.raw
works, we can use it to our advantage:
f=(x,y)=>String.raw({raw:x},...y) // f("abc", "de") => "adbec"
f=x=>String.raw({raw:x},...[...x].keys()) // f("abc") => "a0b1c"
f=(x,y)=>String.raw({raw:x},...y[.repeat(x.length.x].fill(y)) // f("abc", " ") => "a b c"
Of course, for that last one, f=(x,y)=>x.split``.join(y)
is way shorter, but you get the idea.
Here are a couple of riffling functions that also work if x
and y
are of equal length:
f=(x,y)=>String.raw({raw:x.match(/.?/g)},...y)
f=(x,y)=>String.raw({raw:x},...y)+y.slice(-1) // Only works if x.length == y.length
You can learn more about String.raw
on MDN.