DIP 1027---String Interpolation---Community Review Round 1
Petar
Petar
Thu Dec 12 23:31:21 UTC 2019
On Thursday, 12 December 2019 at 17:03:53 UTC, Atila Neves wrote:
> On Thursday, 12 December 2019 at 17:01:01 UTC, Adam D. Ruppe
> wrote:
>> On Thursday, 12 December 2019 at 15:41:54 UTC, aliak wrote:
>>> [...]
>>
>> The javascript version is allowed to return whatever it wants.
>> The default one returns string but you can do other things
>> with it too like return objects or functions or whatever.
>>
>> [...]
>
> It'd be great if you could expand on this with a list of
> examples of what D could do.
Tagged template literals are indeed quite nice in JS. Here's an
example from the chalk npm package [1]:
```js
// Plain template literals (a.k.a. built-in string interpolation):
const str1 = `
CPU: ${chalk.red("90%")}
RAM: ${chalk.green("40%")}
DISK: ${chalk.yellow("70%")}
`;
// Same example but with tagged template literals - more DRY:
const str2 = chalk`
CPU: {red 90%}
RAM: {green 40%}
DISK: {yellow 70%}
`;
// Tagged template literals + interpolation of variables:
const cpu = 90;
const ram = 40;
const disk = 70;
const str3 = chalk`
CPU: {red ${cpu}%}
RAM: {green ${ram}%}
DISK: {yellow ${disk}%}
`;
Here's another example, this case from the es2015-i18n-tag
library [2] that applies translations, locale and currency
formatting:
const name = 'Steffen'
const amount = 1250.33
console.log(i18n`Hello ${ name }, you have ${ amount }:c in your
bank account.`)
// Hallo Steffen, Sie haben US$ 1,250.33 auf Ihrem Bankkonto.
```
The D analog of a function that can be used as tagged template
string literal would be:
```d
string interpolate(Args...)(string[] parts, Args args)
{
import std.algorithm.iteration : joiner;
import std.conv : text;
import std.range : roundRobin;
string[Args.length] stringifiedArgs;
static foreach (idx, arg; args)
stringifiedArgs[idx] = text(arg);
return parts.roundRobin(stringifiedArgs[]).joiner.text;
}
static import term; // Assume some ANSI term coloring library
const string res = i"
CPU: ${term.red("90%")}
RAM: ${term.green("40%")}
DISK: ${term.yellow("70%")}
".interpolate;
```
[1]: https://github.com/chalk/chalk
[2]: https://github.com/skolmer/es2015-i18n-tag
More information about the Digitalmars-d
mailing list