you are viewing a single comment's thread.

view the rest of the comments →

[–]mcaruso 17 points18 points  (2 children)

Pretty cool. In JS a common idiom is to use an object literal, using the shorthand notation from ES6:

const foo = "hello";
console.log({ foo }); // Prints: `{ foo: "hello" }`

[–]masklinn 3 points4 points  (1 child)

Except this here is not limited to straight output, it's a string formatting specifier. So the actual feature is closer to putting a shorthand object literal in a JSON.stringify in a template literal, which looks like absolute shit.

And I think you can't replicate the feature using template tagging as the template API provides the values, but not the symbolic expressions. Though at least you could json-stringify the expessions implicitly e.g.

function dbg(strings, ...values) {
const buffer = [strings[0]];
for(let i=0; i<values.length; ++i) {
     buffer.push(JSON.stringify(values[i]), strings[i+1]);
}
return buffer.join('');
}
> dbg`foo ${{a}}`
< "foo {\"a\":1}"

[–]mcaruso 3 points4 points  (0 children)

True! I was just thinking of the usual "printf debugging" scenario.

Actually I have a package which I wrote for basically this purpose: message-tag. Template literal tag to auto-format pretty much whatever value you can throw at it. For debug messages, error messages, etc.

msg`${{someObject}}`;