tc39 / proposal-extended-numeric-literals

Extensible numeric literals for JavaScript
https://tc39.github.io/proposal-extended-numeric-literals/
72 stars 18 forks source link

Why only numeric? Why not extensible string literals? #3

Closed domenic closed 4 years ago

domenic commented 6 years ago

C++ uses different string literals to great effect.

Example use:

"abcd"utf8 // gives a Uint8Array containing the UTF-8 encoded bytes for the string

(or "abcd"_utf8 if we do #2)

Template tags kind of cover the same space. But I argue they are different:

littledan commented 6 years ago

+1. You're explaining what sort of differences there are between these and tagged templates, but it seems more stylistic than in terms of actual semantics. Do you have any ideas about what semantics may be different, apart from disallowing templated parts?

domenic commented 6 years ago

I mean, they're not very different semantically. I suppose it makes it easy to do `foo${bar}baz`utf8 without having to write the somewhat-tedious string concatenator template tag for utf8 and then write the code that turns it into bytes:

const encoder = new TextEncoder();

function utf8TemplateTag(strings, ...parts) {
    let string = strings[0];
    for (const [i, part] of parts.entries()) {
        string += part;
        string += strings[i+1];
    }
    return encoder.encode(string);
}

vs.

const encoder = new TextEncoder();

function utf8Literal(string) {
    return encoder.encode(string);
}

This helps enforce the fact that you should be using literals when you don't need templating abilities, by making it much easier.

hax commented 6 years ago

Some thought:

  1. String literal seems not have many use cases like numeric literal though utf8 case is very attractive to me.
  2. Suffix form seems not ok for long literal. (you only see it when you read to the end of the line.) And string literal is potentially much longer than numeric literal. I guess this is why python unicode string is u'...' not '...'u, and I would also expect utf8 literal string as utf8'...' 😜
littledan commented 4 years ago

I think @hax made some good arguments for the current design of template literals. This proposal is going to focus on numeric literals and not provide a new kind of string literal.

S-Asakoto commented 4 years ago

Adding to @hax's comments, I think that such prefixes are not needed either, because we already have the tagged literals, and we can safely write u'...' in Python as utf8`...`, similar to String.raw`...` which is already the standard.