Re: Yet another attempt at typed JS data

2020-02-12 Thread Claude Pache
At some point in the algorithm of [Array.from], the newly-created array will 
indeed be created as sparse (at steps 9/10), but this is usually not observable 
(that is, unless you are creating an instance of a subclass of Array with very 
unusual behaviour) as far as the spec is concerned (optimisation is not part of 
the spec).

If it is important for you to circumvent the v8 limitation in its optimisation 
process, you should be able to write `Array.from(Array(2), _ => undefined)`: 
the array will be created as non-sparse at steps 5.a/b.

In any case, this optimisation detail is by very far not a satisfactory 
argument for introducing the heavy feature you proposed. It could maybe be a 
conceivable argument for introducing `Array.createAsNonSparse(2)`.

[Array.from]: https://tc39.es/ecma262/#sec-array.from

—Claude


> Le 12 févr. 2020 à 10:23, Andrea Giammarchi  a 
> écrit :
> 
> Which part of `HOLEY_SMI_ELEMENTS` makes you think so?
> 
> V8 version 8.2.34
> d8> %DebugPrint(Array.from({length: 2}, (_, i) => i))
> DebugPrint: 0x5ab080c5ded: [JSArray]
>  - map: 0x05ab08281869  [FastProperties]
>  - prototype: 0x05ab08248f7d 
>  - elements: 0x05ab080c5dfd  [HOLEY_SMI_ELEMENTS]
>  - length: 2
>  - properties: 0x05ab080406e9  {
> #length: 0x05ab081c0165  (const accessor descriptor)
>  }
>  - elements: 0x05ab080c5dfd  {
>0: 0
>1: 1
>  }
> 0x5ab08281869: [Map]
>  - type: JS_ARRAY_TYPE
>  - instance size: 16
>  - inobject properties: 0
>  - elements kind: HOLEY_SMI_ELEMENTS
>  - unused property fields: 0
>  - enum length: invalid
>  - back pointer: 0x05ab082817f1 
>  - prototype_validity cell: 0x05ab081c0451 
>  - instance descriptors #1: 0x05ab08249605 
>  - transitions #1: 0x05ab08249639 Transition array #1:
>  0x05ab08042e91 : (transition to 
> PACKED_DOUBLE_ELEMENTS) -> 0x05ab08281891 
> 
>  - prototype: 0x05ab08248f7d 
>  - constructor: 0x05ab08248e51 
>  - dependent code: 0x05ab080401ed 
>  - construction counter: 0
> 
> [0, 1]
> 
> On Wed, Feb 12, 2020 at 7:01 AM Jordan Harband  > wrote:
> No, `Array.from` never produces a holey array whatsoever; only ever a dense 
> array.
> 
> On Sun, Feb 9, 2020 at 11:08 PM Andrea Giammarchi 
> mailto:andrea.giammar...@gmail.com>> wrote:
> Unfortunately, `Array.from({ length: 4 }, () => whatever)` produces a holey 
> array, so that the `.repeat(...)` idea, if capable of packing elements in a 
> better way, wouldn't be so terrible, as simplification.
> 
> Although, the intent of this proposal was to also grant "shapes" or kindness 
> of each entry, same way typed Arrays do, but maybe that would require some 
> better primitive, as in `const Shape = Object.defineShape(...)` and 
> `Object.createShape(Shape)` or similar.
> 
> On Sun, Feb 9, 2020 at 10:01 PM Jordan Harband  > wrote:
> That already exists - `Array.from({ length: 4 }, () => whatever)` - I assume 
> that the hope is to have an array where it is *impossible* for it to have the 
> wrong "kind" of data, and a userland factory function wouldn't provide that.
> 
> On Sun, Feb 9, 2020 at 10:39 AM kai zhu  > wrote:
> > It's a bit of a mess to create an Array that is not holed and gets best 
> > optimizations [1], and this proposal would like to address that exact case.
> 
> could the performance issue be resolved more easily with a simple 
> static-function `Array.repeat(, )`?
> 
> ```js
> let structuredList;
> structuredList = Array.repeat(4, function (ii) {
> return {
> index: 2 * ii + 1,
> tags: []
> });
> /*
> structuredList = [
> { index: 1, tags: [] },
> { index: 3, tags: [] },
> { index: 5, tags: [] },
> { index: 7, tags: [] }
> ];
>  */
> ```
> 
> the only time i can practically enforce the shape of a "StructuredArray" is 
> during element-insertion,
> and a userland insertion/creation function would be just as effective as a 
> StructuredArray constructor.
> 
> enforcing shapes during element deletions and updates are going to be hard
> and likely just as confusing with StructuredArray as they are with regular 
> Array.
> 
> also note that most javascript arrays need to be easily JSON-serialized for 
> message-passing
> over-the-wire (commonly http) to external systems.
> 
> -kai
> 
> On Sat, Feb 8, 2020 at 3:46 AM Andrea Giammarchi  > wrote:
> > having to retroactively add checks like...
> 
> we already have typed arrays in JS so I don't think this would be any 
> different
> 
> > I _think_ that moderns virtual machines already did these optimisations 
> > despite there isn't a TypedArray like that.
> 
> It's a bit of a mess to create an Array that is not holed and gets best 
> optimizations [1], and this proposal would like to address that exact case.
> 
> [1] https://v8.dev/blog/elements-kinds 
> 
> 
> 
> 
> ___
> es-discuss mailing list
> 

Re: Array.prototype.toggle

2020-02-07 Thread Claude Pache


> Le 7 févr. 2020 à 14:52, Claude Pache  a écrit :
> 
> 
> 
>> Le 7 févr. 2020 à 13:23, manuelbarzi > <mailto:manuelba...@gmail.com>> a écrit :
>> 
>> calling it again would just apply the same mechanism => "do this element 
>> already exist? "remove it" : "add it". in the example, it would just add 1 
>> at the end of array (i.e. just a push), calling it the second time.
> 
> Probably `Array.prototype.remove` would be a more appropriate name for what 
> you suggest.

Sorry, I somewhat misread your message. So:

The DOMTokenList array-like interface has a `toggle` method, and some others 
like `add`, `remove`, etc.

https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList 
<https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList>

Although, as I said, in such situations, I tend to use a Set instead of an 
Array.

Maybe it would make sense to add a `toggle` method to `Set.prototype`?

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Array.prototype.toggle

2020-02-07 Thread Claude Pache


> Le 7 févr. 2020 à 13:23, manuelbarzi  a écrit :
> 
> calling it again would just apply the same mechanism => "do this element 
> already exist? "remove it" : "add it". in the example, it would just add 1 at 
> the end of array (i.e. just a push), calling it the second time.

Probably `Array.prototype.remove` would be a more appropriate name for what you 
suggest.

The DOMTokenList array-like interface has such a `remove` method (and some 
others):

https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList 


Although, in situations where I am in a need of a `remove` method, I tend to 
use a Set instead of an Array.

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: syntax for case ranges

2020-02-03 Thread Claude Pache
Try typing `3 < 2 < 1` in the web console of your favourite browser, and see 
the result: it will evaluate to `true`. No, your browser isn’t buggy, it is 
just following blindly the semantics of `<`.

Modifying the meaning of `3 < 2 < 1` in order to make it evaluating  to `false` 
is a BC break. Is it acceptable? Dunno.

—Claude

> Le 3 févr. 2020 à 15:23, Naveen Chawla  a écrit :
> 
> Hi!
> 
> I didn't understand your reply.
> 
> I think currently it would raise an error, because 1 < 2 < 3 is currently 
> saying (probably) true < 3.
> 
> But a "new" syntax could possibly parse that as a "chain" of comparisons.
> 
> Would this be acceptable to introduce into JavaScript (just curious)?
> 
> I've probably missed your point entirely, because I saw a short message "3 < 
> 2 < 1 //true", and I've assumed you meant it in reverse.
> 
> On Sat, 1 Feb 2020 at 23:12, Mark S. Miller  > wrote:
> 3 < 2 < 1;  // true
> 
> 
> On Sat, Feb 1, 2020 at 3:03 AM Naveen Chawla  > wrote:
> Certain languages allow the expression 0 be syntactically possible in JavaScript? Of course this would only apply for 
> "if"/"while" statements.
> 
> On Fri, 31 Jan 2020 at 22:41, Isiah Meadows  > wrote:
> Still better to discuss it there - it's highly related to your suggestion. 
> And I'm pretty sure an issue already exists related to that.
> 
> On Fri, Jan 31, 2020 at 09:06 Sultan  > wrote:
> The pattern matching proposal does not handles the mentioned case:
> 
> switch(type) { case 0...5: } being the equivalent of switch(type) { case 0: 
> case 1: case 2: case 3: case 4: case 5: }
> 
> On Fri, Jan 31, 2020 at 7:36 PM Bruno Macabeus  > wrote:
> I agree with Oriol.
> We already have the proposal pattern matching, that has a very similar effect.
> I think that is better to improve pattern matching proposal in order to be 
> able to match using ranges (or at least check if it's good to do) instead of 
> create a new proposal.
> 
> On Fri, 31 Jan 2020 at 14:08, Oriol _  > wrote:
> This sounds like https://github.com/tc39/proposal-pattern-matching 
> 
> 
> El 31/1/20 a les 10:57, Sultan ha escrit:
>> For example, the following:
>> 
>> switch (value) {
>> case 0...9: break
>> case 'a'...'z': break
>> }
>> 
>> 
>> ___
>> es-discuss mailing list
>> es-discuss@mozilla.org 
>> https://mail.mozilla.org/listinfo/es-discuss 
>> 
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 
> -- 
> -
> 
> Isiah Meadows
> cont...@isiahmeadows.com 
> www.isiahmeadows.com 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 
> 
> 
> -- 
>   Cheers,
>   --MarkM
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: strict built-in functions

2019-12-09 Thread Claude Pache


> Le 8 déc. 2019 à 15:39, Mark S. Miller  a écrit :
> 
> Wow, Edge is definitely in violation of the intent of the spec, and the 
> intent of the history of treatments of .caller in previous discussions and 
> specs over the years. The Edge behavior is grossly unsafe.
> 
> Hi Jack, thanks for catching this and raising it!! It does need to be fixed. 
> I do think it can be a PR because the historical intent was clear. Since the 
> FF behavior is correct, the correct behavior is web compat, so we should be 
> able to handle this in a PR.
> 
> Whether a PR or a full proposal, in either case I'm happy to take this to the 
> committee. I invested years of my life killing non-sloppy function.caller. I 
> can spend a little more ;)

Hi Mark,

I think it is time to revive https://github.com/tc39/ecma262/issues/562 
 and its associated repo 
https://github.com/claudepache/es-legacy-function-reflection 
.

—Claude


___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: strict built-in functions

2019-12-09 Thread Claude Pache


> Le 8 déc. 2019 à 20:49, Jack Works  a écrit :
> 
> I thought the "caller" has been removed from the spec, so there isn't much to 
> do with the "caller" since it is not standard. It's implementation's own 
> extension.
> But maybe we can also extend The forbidden extensions section.

The `caller` property of functions (not to be confused with the `caller` 
property of the `arguments` object, which is indeed dead) has never been in the 
spec, except some restrictions in the [Forbidden Extensions] section introduced 
at the same time as strict-mode functions. And the problem is, precisely, that 
it is underspecified.

Now, it is indeed almost trivial to resolve spec-wise *the particular* issue 
you noted, by amending the [Forbidden Extensions] section: Just find the bullet 
that begins with “If an implementation extends any function object with an own 
property named "caller"...”, and replace therein all occurrences of “strict 
function” with “strict function or built-in function” (or maybe with “anything 
but a non-strict function”). That, however, is not the most 
implementation-friendly way, because that leaves up to them to guess what to do 
instead (return null, throw an error, etc.), that will not break the web for 
their users. 

Moreover, the `caller` property has most probably some other gotchas; one of 
them I recall to have noted some time ago, is that, in at least one 
implementation, it is publicised as a non-writable, non-configurable own data 
property, but it may change its value.

I think that it is better, at this point, to specify Function#caller and 
Function#arguments, as proposed in [gh-issue 562].

[Forbidden Extensions]: https://tc39.es/ecma262/#sec-forbidden-extensions 
<https://tc39.es/ecma262/#sec-forbidden-extensions>
[gh-issue 562]: https://github.com/tc39/ecma262/issues/562 
<https://github.com/tc39/ecma262/issues/562>

—Claude


> 
> On Mon, Dec 9, 2019, 1:12 AM Claude Pache  <mailto:claude.pa...@gmail.com>> wrote:
> 
> 
>> Le 8 déc. 2019 à 14:43, Jack Works > <mailto:zjwpe...@gmail.com>> a écrit :
>> 
>> 
>> In the current spec, strictness of the built-in functions are 
>> implementation-dependent behaviors. This proposal is going to fix this 
>> problem.
>> https://github.com/Jack-Works/proposal-strict-built-in-functions 
>> <https://github.com/Jack-Works/proposal-strict-built-in-functions>
>> 
> 
> Hi,
> 
> See https://github.com/tc39/ecma262/issues/562#issuecomment-218531285 
> <https://github.com/tc39/ecma262/issues/562#issuecomment-218531285> for 
> another  testcase. 
> 
> The real problem is that the semantics of `f.caller` is left to 
> implementations. There are in fact some restrictions in the spec, see 
> https://tc39.es/ecma262/#sec-forbidden-extensions 
> <https://tc39.es/ecma262/#sec-forbidden-extensions>, but they are 
> insufficient.
> 
> Note that it doesn’t really make sense to mandate that builtin functions be 
> “strict”: The notion of strictness is defined only for so-called ECMAScript 
> functions, which are functions whose implementation is written in ECMAScript 
> code. That excludes builtin functions (unless the implementation choose to  
> implement them in ECMAScript), but also bound functions, proxies, and 
> probably some other cases. 
> 
> —Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: strict built-in functions

2019-12-08 Thread Claude Pache


>> Le 8 déc. 2019 à 14:43, Jack Works  a écrit :
> 
> In the current spec, strictness of the built-in functions are 
> implementation-dependent behaviors. This proposal is going to fix this 
> problem.
> https://github.com/Jack-Works/proposal-strict-built-in-functions
> 

Hi,

See https://github.com/tc39/ecma262/issues/562#issuecomment-218531285 for 
another  testcase. 

The real problem is that the semantics of `f.caller` is left to 
implementations. There are in fact some restrictions in the spec, see 
https://tc39.es/ecma262/#sec-forbidden-extensions, but they are insufficient.

Note that it doesn’t really make sense to mandate that builtin functions be 
“strict”: The notion of strictness is defined only for so-called ECMAScript 
functions, which are functions whose implementation is written in ECMAScript 
code. That excludes builtin functions (unless the implementation choose to  
implement them in ECMAScript), but also bound functions, proxies, and probably 
some other cases. 

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Can we improve async JavaScript error handling?

2019-12-02 Thread Claude Pache


> Le 29 nov. 2019 à 21:05, Lars Eidnes  a écrit :
> 
> 
> 
> 1) Is it a good idea to introduce an alternative to setTimeout, where the 
> distinction is that it returns a Promise, and that return/throw in the 
> callback take the role of resolve/reject?

I think so (although there is no need keep the callback). But since 
setTimeout() is not part of ECMAScript proper, this is not the proper place to 
discuss it. See rather:

https://github.com/whatwg/html/issues/617 



> 
> 2) Are there other things we could do to minimize the need for 
> resolve/reject? 
> 

I don’t think there is anything to do at the core language level, because it 
has already the necessary tools (async/await). Rather, new APIs ought to be 
designed in order to be directly usable with `await`, i.e., they ought to 
return a Promise instead of taking a callback or having an event-handler. F.e., 
the old XMLHttpRequest API shall be replaced with the new Fetch API.

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Ternary operator enhancement proposal

2019-11-13 Thread Claude Pache


> Le 13 nov. 2019 à 03:43, devlato  a écrit :
> 
> Hey folks,
> 
> not sure if you haven't discussed something similar, but what do you think 
> about making an enhancement for the ternary operator, to make it more 
> powerful? 
> I've created a small explanatory doc on GitHub: 
> https://github.com/devlato/proposal-ternary-placeholder
> 
> Warmest regards,
> Denis
> 

The generic problem is: you do some computation, and you want to reuse the 
result of that computation later.

The generic solution is to use a temporary variable:

```js
// declare a temporary variable at the top of some scope
var _;

// later, use it:
const X = () => (_ = x?.y?.z) ? doSomethingWithValue(_) : null;
```

Now, you are not satisfied with the existing solution, and you want to avoid 
declaration of temporary variables in some outer scope...? Maybe:

```js
const X = () => (#1 = x?.y?.z) ? doSomethingWithValue(#1) : null;
```

(Any similarity with 
https://developer.mozilla.org/en-US/docs/Archive/Web/Sharp_variables_in_JavaScript
 

 is not at all fortuitous.) However, I’m not convinced that the need to declare 
your temporary variables is such a problem that it is worth the introduction of 
new syntax.


—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Optional chaining syntax but with the "mice" operator ?

2019-09-06 Thread Claude Pache


> Le 6 sept. 2019 à 14:35, Felipe Nascimento de Moura  
> a écrit :
> 
> Doesn't that bring risks to breaking the web?
> 
> You seen, many, MANY servers running php have the "shot-tags" feature 
> enabled, in which pages with  will be interpreted.
> In this case, any html page with embedded scripts using this operator, or 
> event .js files when the server is configured to also run php in them, will 
> break.
> 
> Or am I missing something here?
> 
> [ ]s
> 

Any future PHP file that incorporate that syntax will almost surely refuse to 
compile on servers that has short-tags enabled, making the problem evident 
before it produces something useful on the web. This may be an issue, but this 
is not what “breaking the web” is intended to mean. Existing, untouched content 
will not break. Carelessly updated content might break, but that’s not 
fundamentally different from any other careless update.

(If anything else, it may convince people that having different configuration 
settings w.r.t. short-tags in development environment and in production 
environment, is a very bad idea...)

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Optional chaining syntax but with the "mice" operator ?

2019-09-06 Thread Claude Pache


> Le 5 sept. 2019 à 23:39, Andrea Giammarchi  a 
> écrit :
> 
> This is basically a solution to a common problem we have these days, where 
> modules published in the wild might have a `default` property, to support ESM 
> logic, or not.
> 
> ```js
> // current optional chaining logic
> const imported = exported?.default ?? exported;
> 
> // my "mice operator" proposal
> const imported = exported ```
> 


The semantics of the `?.` in `exported?.default` is not to check whether the 
`default` property exists, but whether `exported` evaluates to undefined or 
null. If the `default` property is absent, `exported.default` has always 
evaluated to `undefined`, and there is no need to optional chaining operator. 
So that I guess you actually meant:

``js
const imported = exported.default ?? exported;
```


—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Async Class

2019-08-27 Thread Claude Pache


> Le 26 août 2019 à 17:11, Dimitrian Nine  a écrit :
> 
> Class is just function constructor that return object

Although in JS a class is represented by the same object as its constructor, I 
don’t think it is good to assimilate the concept of JS class and JS 
constructor. Indeed, a class consists not only of its constructor, but also of 
all its associated methods. This is what is suggested by the syntax:

```js
class C { 
/* definition of all methods, not only constructor */ 
}
```

From that perspective, I understand very well what would be an “async 
constructor”; but an “async class” doesn’t make much sense.

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Modulo Operator %%

2019-08-15 Thread Claude Pache


> Le 12 août 2019 à 22:00, Matthew Morgan  a écrit :
> 
> JS needs a modulo operator. It currently has the remainder operator `%` which 
> works in most cases except for negative values. I believe the the `%%` would 
> work great and be easy to remember. 
> 
> let x = (-13) %% 64;
> is equivalent to  
> let x = ((-13 % 64) + 64) % 64;

Is there a strong advantage of an `%%` operator over a `Math.mod()` function? 
There is the precedent of the `**` operator implemented as alternative of 
`Math.pow()` few years ago. It would be interesting to hear the feedback of 
those that use regularly powers, whether the benefit was clear (personally, I 
almost never use either `Math.pow()` or `**`, so that I can’t say anything).

At least one disadvantage of an operator over a function, is that you have to 
think about precedence. The problem is exacerbated in JS, because (following 
some other languages) the unary minus has an uncanny high precedence level, 
confusingly very different than the one of the binary minus; so that, after 
having designed `**`, it was realised at the last minute that `-a**b` would be 
dumbly interpreted as `(-a)**b` instead of `-(a**b)` or `0-a**b`, as anybody 
who would be likely to actually use the operator would expect. (That particular 
issue was resolved in a hurry by making the parenthesis-left form a syntax 
error.)

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: `String.prototype.codePointCount`

2019-08-08 Thread Claude Pache

> Le 8 août 2019 à 11:07, fanerge  a écrit :
> 
> There are many such requirements in a real development scenario, such as how 
> many characters are allowed to be entered by the user, which is something we 
> should consider not in Unicode for Basic Multilingual Plane.


I have cases where I want to limit the length of user input, for which purpose 
I just use , although it gives inconsistent results across the 
three browsers I have tested: two of them limit the number of UTF-16 code 
units, one of them limits the number of grapheme clusters (and none of them 
limit the number of code points).

In fact, for my purpose, I have no reason to impose a limit for a precise 
number of *code points* (as opposed to other possible definitions of “length” 
such as *UTF-16 code units* or *grapheme clusters*). Technically, I am usually 
limited by the size of a column in the database, for which the “size” 
corresponds typically to the number of bytes in a UTF-8 encoded string. From a 
user point-of-view, the number of “characters” is better approximated by the 
number of grapheme clusters. None of those two notions of “length” correspond 
to the number of code points.

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: `String.prototype.codePointCount`

2019-08-08 Thread Claude Pache
> Le 8 août 2019 à 04:37, fanerge  a écrit :
> 
> I expect to be able to add an attribute to String.prototype that returns the 
> number of codePoints of the string to reflect the actual number of characters 
> instead of the code unit.

Note however that “the number of code points” is not the same thing as “the 
actual number of characters” for what a human usually perceives as “character”. 
For example:

```js
Object.defineProperty(String.prototype, "codePointCount", {
get() { return [...this].length }
})
"".codePointCount // 2
"n̈".codePointCount // 2
"é".codePointCount // 1
"é".normalize("NFD").codePointCount // 2
```

> 
> I believe that most developers need such a method and property to get the 
> number of codePoints in a string.
> 

For what purposes do “most developers” need the number of code points?

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Removing the space in `a+ +b`?

2019-06-28 Thread Claude Pache


> Le 28 juin 2019 à 19:03, guest271314  a écrit :
> 
> Reversing the order does not require a space character
> 
> ```
> +b+a
> ```

If you have `+a + +b`, reversing order is not interesting. 

But more importantly, there is no point into searching for a solution unless 
there is a problem. What is the problem with that space?

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Removing the space in `a+ +b`?

2019-06-28 Thread Claude Pache

> Le 28 juin 2019 à 17:41, Isiah Meadows  a écrit :
> 
> Currently, the production `a+ +b` requires a space to disambiguate it from 
> the increment operator. However, `a++b` is not itself valid, as the postfix 
> increment cannot be immediately followed by a bare identifier on the same 
> line, nor can a prefix operator be preceded by one on the same line. Could 
> the grammar be amended to include this production and make it evaluate 
> equivalently to `a+ +b`
> 
> AdditionExpression :: AdditionExpression `++` [no LineTerminator here] 
> UnaryExpression
> -- 
> -
> 
> Isiah Meadows
> cont...@isiahmeadows.com 
> www.isiahmeadows.com 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss


What is the motivation (apart obfuscation contests, as in: `ab`)?

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Exposing native scroll as API

2019-06-21 Thread Claude Pache


> Le 21 juin 2019 à 16:07, Adam Eisenreich  a écrit :
> 
> Hello everyone. I think browsers should expose the native scroll as API. 
> 
> Possible uses:
> * Native-like scroll in canvas apps (games) - Google's Proxx 
> (https://proxx.app/) had to do quite a bit of magic to have native scroll for 
> a game.
> * Camera controls for touch device (3D model preview)
> Gesture recognition (maybe)
> * Infinite scroll (they could get rid of the invisible long div, that makes 
> the scrolling inside possible) - Angular virtual scroll implementation 
> https://material.angular.io/cdk/scrolling/overview 
> 

Scrolling is not part of ECMASCript (the core language), but is provided by a 
Web API. This is out of the scope of this mailing list.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Symbol.inObject well-known symbol to customize the "in" operator's behavior

2019-05-09 Thread Claude Pache


> Le 9 mai 2019 à 23:17, Tom Barrasso  a écrit :
> 
> If this Symbol were seriously considered I believe it would expand the 
> meaning of the in operator as you’re correct, this is definitely not it’s 
> current intention.
> 


The `in` operator has a well-defined meaning, that by design you can’t ignore 
even with the fanciest proxy. (And no, there is no hope for introducing a new 
mechanism that allows to overcome those limitations, since they are by design.)
Consider for example the following proxy around a String object:

```js
function conflateInAndIncludes(str) {
return new Proxy(Object(str), { 
has(target, key) { return str.includes(key) } 
})
}

var FrankensteinFood = conflateInAndIncludes("food");

"foo" in FrankensteinFood // true, yeah!
"bar" in FrankensteinFood // false, yeah!
"length" in FrankensteinFood // TypeError: proxy can't report a 
non-configurable own property '"length"' as non-existent
```


—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Symbol.inObject well-known symbol to customize the "in" operator's behavior

2019-05-09 Thread Claude Pache


> Le 9 mai 2019 à 20:52, Tom Barrasso  a écrit :
> 
> Like Symbol.hasInstance but for the "in" operator.
> This symbol would work for both native and user-defined objects.
> 
> *Example implementation* prototyping native object:
> 
> ```js
> String.prototype[Symbol.inObject] =
>   function(searchString) {
> return this.includes(searchString)
> }
> ```
> 
> *Example implementation* for user-defined object:
> 
> ```js
> function range(min, max) => ({
> [Symbol.inObject]: (prop) => {
> return (prop >= min && prop <= max)
> }
> })
> ```
> 
> *Example usage*:
> 
> ```js
> ("foo" in "food")// true
> (14 in range(1, 25)) // true
> ```

Those two examples seem to give to the `in` operator a meaning that it was not 
intended to have. The `in` operator is specifically meant to check whether a 
given property exists in a given object.

Also, there already exists a way to customise the behaviour of the `in` 
operator, namely by using a Proxy.

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Static Typing

2019-03-27 Thread Claude Pache


> Le 27 mars 2019 à 18:26, Michael Theriot  a 
> écrit :
> 
> Would an error at runtime or compiletime occur here?
> 

The check cannot be reliably done at compile time in general; it must be a 
runtime check. (Tools may provide partial static analysis, but that’s an extra.)

The simplest reason is that statically typed code must run together with 
non-statically typed code.

And even ignoring legacy code, it is not desirable to have static types 
everywhere; for instance, `Array.prototype.sort()` must continue to work with 
both arrays of strings and arrays of numbers, and even with arrays of mixed 
types.

And even if everything everywhere was statically typed, you still cannot 
statically analyse situations like: `a = object[Math.random() < 0.5 ? 
"method_returning_number" : "method_returning_string"]()`.

> If it is a runtime error, is it optimal for the engine to keep track of typed 
> variables vs regular for the same value?

Today’s JS engines typically do already clever speculative optimisations based 
on expected types. For example: https://stackoverflow.com/a/46144917 
. So, I guess, it depends...

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Dash-case keys

2019-01-28 Thread Claude Pache


> Le 29 janv. 2019 à 08:45, Sultan Tarimo  a écrit :
> 
> That is obj.font-size would rightly be invalid. 

Sadly, `obj.font-size` is *not* invalid, it has some well-defined semantics. 
That would be a source of bugs

 —Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Class Templates

2019-01-16 Thread Claude Pache


> Le 16 janv. 2019 à 13:57, ViliusCreator  a écrit 
> :
> 
> “Strongly typed” Strongly typed is not Statically typed. Python is strongly 
> typed for example. Strongly typed language means that `”something” + 1` will 
> throw error, Weakly typed means that `”something” + 1` will turn `1` into 
> string and add it to `something`, which will result in `something1`.
> 
> Statically typed language means that once you do `Boolean Abc = true`, or 
> `let Abc: Boolean = true`, you can’t change it to number, but you can change 
> it to `false`, or `true`.
>  
> Did you mean Statically typed language?
> 
> Also, I think that there can be usefulness in class templates, without 
> language being Statically typed.

I meant ”statically typed”, yes. But I think you understood what I meant. My 
question was about compelling use cases in JS. We know that you think it is 
useful, but you should convince others that it is useful, that is to say, worth 
the added complexity in the language.

 —Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Class Templates

2019-01-16 Thread Claude Pache
From what I understand (that is, not much), class templates are useful in 
strongly typed languages, so that one can have a family of classes that share 
the same implementation but that derive from different types; e.g. Stack 
for stacks of ints and Stack for stacks of strings. In JS, you can have 
one Stack class that accepts both ints and strings, so that this use case 
doesn’t apply (or, at least, it is not a necessity).

But I'm sure there are other use cases. What are they, and are they compelling 
enough?

—Claude

> Le 15 janv. 2019 à 19:59, IdkGoodName Vilius  a 
> écrit :
> 
> See: 
> https://github.com/CreatorVilius/ecmascript-proposals/blob/master/proposal-class-templates.md
>  
> 
>  
> I think having Class Templates in JavaScript would be awesome thing and 
> should be implemented. But that’s just my opinion.
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Placeholder operator

2019-01-11 Thread Claude Pache


> Le 11 janv. 2019 à 14:02, Sultan  a écrit :
> 
> Placeholder operator: !
> 
> Use in function parameters(maintains arity without creating a named binding):
> 
> const foo = (a, b, !) => {}

Today, you can write:

```js
const foo = (a, b, _) => { }
```

Is the complexity added to the language worth the feature?

> 
> Use in de-structuring(allows you to capture further along a tuple without 
> creating a named binding):
> 
> const [!, setState] = useState(0)

You can already write:

```js
const [ , setState] = useState(0)
```

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: String identity template tag

2018-12-13 Thread Claude Pache
Random suggestions:

* `String.cooked`, which pairs well with already existing `String.raw`
* `String.vanilla`
* `String.plain`
* `null`, i.e., using a null (or undefined) value as tag before a template 
literal is equivalent to using no tag. (Con: not polyfillable)

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: New: proposal-safe-prototype

2018-11-28 Thread Claude Pache
Sorry, I didn’t read the thread thoroughly (so maybe I’ll repeat someone). But 
here are some serious  issues with your proposal:

--

1. Assignment of properties deep in the object hierarchy split in two 
instructions:

```js
var a = { __proto__: { foo: { bar: 2 } } } with safe-prototype;
var b = a.foo;
b.bar = 3;
```
Should the last line trigger copy-on-write around `a.__proto__`?

If you say ”no”, it means that the meaning of the code is changed unexpectedly 
with an apparent innocuous code refactoring.

If you say ”yes”, it is dreadful action-at-distance, because the two last lines 
of code may be very distant, indeed even in two distinct files. — It would be 
less an issue if prototypes were, say, just abstract templates. But they are 
not, they are concrete objects, so:

```js
var proto = { foo: { bar: 2 } };
var a1 = { __proto__: proto } with safe-prototype;
var a2 = { __proto__: proto } with safe-prototype;
var b1 = a1.foo;
var b2 = a2.foo
b1 === b2; // true
b1.bar = 3;
b1 === b2; // ???
```

--

2. Object mutations unrelated to the value of its properties:

```js
var a = { __proto__: { foo: new Map([ [ 'bar', 2 ] ]) } } with safe-prototype;
a.foo.set('bar', 3);
```

Unless you have deep knowledge of the internal state and/or the implementation 
of the modified object (which you don’t have in case of a user-implementated 
one), you cannot reliably detect when an object is mutated.

Note the subtle difference between:
*  `[].push(1)` — You will detect object mutation, because it will add a 
concrete property on the Array object.
* `(new Set).add(1)` — You won’t detect mutation, because only internal state 
of the Set object is modified.
* `(new RandomUserDefinedCollection).put(1)` — That depends on the 
implementation of the `RandomUserDefinedCollection` class.



—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: New Proposal: Placeholder syntax

2018-11-28 Thread Claude Pache


> Le 28 nov. 2018 à 19:17, Andrew Kaiser  a écrit :
> 
> Hi all,
> 
> I have created a short proposal to introduce syntactic sugar for anonymous 
> functions in a 'scala-like' manner, linked here 
> https://github.com/andykais/proposal-placeholder-syntax 
> .
> 
> I am hoping to hear feedback on whether or not this is interesting to people, 
> as well as feedback on the proposal itself (e.g. is there a better operator 
> to use than ` * `)


See the previous discussion on this topic:

https://esdiscuss.org/topic/syntax-proposal-anonymous-arguments

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal for faster this assignments in constructor functions

2018-11-28 Thread Claude Pache

> Le 28 nov. 2018 à 19:32, Simo Costa  a écrit :
> 
> In costructor functions and in the constructor() method in ES6 classes is 
> easily to fall in the following pattern:
> 
> F(par1, par2, ..., parN) {
>   this.par1 = par1;
>   this.par2 = par2;
>   ...
>   this.parN = parN;
> }
> 
> So my proposal is to avoid those repetitions  by prefixing a dot . to each 
> parameter:
> F(.par1, .par2, ..., .parN) {}
> 
> Simple but quite useful. More info here: 
> https://github.com/jfet97/proposal-fast-this-assignments 
> 
> 

Simple, but a brand new and nonobvious syntax, for a relatively limited use 
case.

Also, just one dot is too inconspicuous. At the very least, I’d prefer:

```js
function F(this.par1, this.par2, this.par3) { }
```

whose meaning is somewhat more intuitive.


Also noteworthy: in many cases, you can already reduce repetition with the 
combination of `Object.assign`, improved syntax literal, and imagination; see:

http://2ality.com/2014/12/es6-oop.html#use-cases-for-objectassign


—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Expectations around line ending behavior for U+2028 and U+2029

2018-10-26 Thread Claude Pache


> 
> Would it be worth exploring a definition of U+2028/29 in the spec such that 
> they behave as line terminators for ASI, but otherwise do not increment 
> things line number counts and behave as whitespace characters?

Diverging the definition of line terminator for the purpose of line counting on 
one side, and ASI and single-line comment on the other side, is adding yet 
another complication in a matter that is already messy. And I suspect that most 
tools that have issues with the former case, have issues as well with the 
latter case, so that half-fixing is equivalent to not fixing.

If we want to ”fix” the definition of line terminator somewhere, we should 
”fix” it everywhere.

(Note that the recent addition of U+2028 and U+2029 inside string literals does 
not constitutes a modification of the definition of line terminator in that 
context; it is rather allowing string literals to span multiple lines in some 
specific cases.)

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Expectations around line ending behavior for U+2028 and U+2029

2018-10-26 Thread Claude Pache


> Le 24 oct. 2018 à 21:58, Logan Smyth  a écrit :
> 
> On the other hand, it seems like every editor that I've looked at so far will 
> not render these characters as newlines,

I have just tried to open a file containing U+2028 and U+2029 in four different 
text editors / integrated environments on my Mac. All of them recognise both 
characters as newlines (and increment the line number for those that display 
it).

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Array.prototype.remove(item)

2018-10-10 Thread Claude Pache


> Le 10 oct. 2018 à 23:17, kai zhu  a écrit :
> 
> hi Man, i don’t have strong opinion on Array.prototype.remove, but i have 
> strong opinion against your use-case to subclass/extend Array.  from a 
> product-development perspective, you're creating unnecessary 
> integration-headaches by having the client <-> server system pass around 
>  instances instead of plain JSON arrays.

Not every object in JS is intended to travel between client and server, or to 
be stored in JSON. And if/when the class want to share some information, it can 
easily translate its data to and from a JSON-friendly format. (Sorry, I’m not 
motivated to read the rest of your e-mail.)

—Claude 

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Array.prototype.remove(item)

2018-10-10 Thread Claude Pache
For that specific example, I think that a Set is more appropriate:

``` js
export class Selector {
private _set = new Set;
 
get values(): ReadonlyArray {
return Array.from(this._set);
// although it might be better to return an iterator: return 
this._set.values();
}

deselect(value: T): boolean {
if (this._set.delete(value)) {
this.selectionChanged([], [value]);
return true;
}
return false;
}

// etc.
}
```

More generally, each time you are tempted to use an 
add()/remove()/toggle()/contains()/etc() method on an Array, you should ask 
yourself if it would not be better (more efficient, clearer intent, more 
concise, ...) to use a Set instead.

—Claude


> Le 10 oct. 2018 à 08:30, Man Hoang  a écrit :
> 
> The benefits are
> - efficient (memory & speed)
> - clear intent
> - concise
>  
> There are always use cases where you want to mutate arrays.
>  
> How would you rewrite the following `deselect` method using `filter`?
>  
> ``` js
> export class Selector {
> private _values: T[] = [];
>  
> get values(): ReadonlyArray {
> return this._values;
> }
>  
> /**
>  * Removes [value] from the list of selected items.
>  * 
>  * Returns `true` if [value] was previously selected, `false` otherwise.
>  */
> deselect(value: T): boolean {
> if (this._values.remove(value)) {
> this.selectionChanged([], [value]);
> return true;
> }
> return false;
> }
>  
> /**
>  * Adds [value] to the list of selected items.
>  * 
>  * Returns `true` if [value] was not previously selected, `false` 
> otherwise.
>  */
> select(value: T): boolean {
> if (this._values.pushIfAbsent(value)) {
> this.selectionChanged([value], []);
> return true;
> }
> return false;
> }
>  
> protected selectionChanged(addedValues, removedValues) {
> // Do something such as firing an event.
> }
> }
> ```
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Object.assign interaction with __proto__ field.

2018-09-26 Thread Claude Pache


> Le 26 sept. 2018 à 16:27, Mike Samuel  a écrit :
> 
> Might it be a spec bug that in the below, o's prototype changes, and o.x !== 
> b.x?
> 
> const a = makeIntercepter();
> const b = { x: 1 };
> const o = Object.assign(
>   {},
>   a,
>   b);
> 
> console.log(`o is plain Object: ${ Object.getPrototypeOf(o) === 
> Object.prototype }`);
> 
> console.log(`b.x=${ b.x }, o.x=${ o.x }`);
> 
> function makeIntercepter() {
>   return JSON.parse(
> // Get an object that has an actual "__proto__" property.
> '{ "__proto__": {} }',
> // Replace the __proto__ property's value with one that
> // traps assignment to x.
> (key, value) => (
>   (key === '__proto__')
> ? {
> set x(v) {
>   console.log(`intercepted ${ v }`);
> },
> get x() {
>   return 2;
> },
>   }
> : value));
> }
> 
> In modern Chrome, Firefox, Safari I get
> intercepted 1
> getPrototypeOf(o)===Object.prototype: false
> b.x=1, o.x=2
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss 
> 

臘 It’s not a bug. But you definitely convinced me to add `delete 
Object.prototype.__proto__` at the top of my JS.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Trigger `catch`/`finally` with rejected `return` promise in `async` functions

2018-09-10 Thread Claude Pache


> Le 9 sept. 2018 à 23:49, Isiah Meadows  a écrit :
> 
> Does `return foo` not seemingly imply the implicit unwrapping is
> occuring *inside* the function?

For me, no. If I want to await the resolution of the promise `foo` before 
handling the `catch` or the `finally` block, I expect to add an explicit 
`await`.

”Intuition” may vary among people. I think that, in general, it is better to 
use the more objective notion of ”regularity”, which is, in this case: ”Always 
use an explicit `await` (or `Promise.all`, etc.) if, at this point of the 
program, you want to await the resolution.”

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: __line_number__ and __filename__

2018-08-24 Thread Claude Pache


> Le 24 août 2018 à 05:55, J Decker  a écrit :
> 
> On Thu, Aug 23, 2018 at 5:26 PM Aaron Gray  > wrote:
> I am debugging existing code that I have modularized, and am class'izing that 
> has unittests and it just would have been very useful to have this facility.
> In a  browser, console.log is usually associated with the file and line 
> number anyway; which includes using devtools with node but it would be 
> handy for logging.  with V8 there is console.trace; which spits out the stack 
> trace too... before I discovered that I did a logging function like... 
> 
> (from  
> https://stackoverflow.com/questions/591857/how-can-i-get-a-javascript-stack-trace-when-i-throw-an-exception
>  
> 
>  )
> function stackTrace() { var err = new Error(); return err.stack; }  // parse 
> stack to get frame-1 online
> 
> // or maybe just frame-1...
> function stackTrace() { var err = new Error(); return err.stack.split( "\n" 
> )[1]; }  
> 
> ---
> function stacktrace() { 
>   function st2(f) {
> return !f ? [] : 
> st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + 
> f.arguments.join(',') + ')']);
>   }
>   return st2(arguments.callee.caller);
> }
> 
>  EDIT 2 (2017) :
> 
> In all modern browsers you can simply call: console.trace(); (MDN Reference)
> ---
> 
> Although I do still miss just being able to get __FILE__ and __LINE__ 


See also:

https://github.com/tc39/proposal-error-stacks 


If/when that proposal is implemented, you'll have a simple way to get a 
*structured* representation of the trace:

```js
System.getTrace(new Error)
```

from which you can much more easily extract line number, filename, etc.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: let-in if do-expr is problematic? (was: Re: proposal: let in if parentheses)

2018-08-22 Thread Claude Pache


> Le 21 août 2018 à 21:20, Herbert Vojčík  a écrit :
> 
> Hi!
> 
> It would be nice to know if do expressions have some a chance, otherwise some 
> other syntax for let-in would be really helpful, especially now that we have 
> arrow functions.
> 
> I would propose to use different variant of let (maybe also const):
> 
> OP 1:
> 
>  let in a = b(), if (a) a.c();
> 
> OP 2:
> 
>  let in a = b(), if (a) c(a);
> 
> Instead of
>  const big = raw => {
>let cooked = cook(raw);
>return consumer => {
>  // do things with consumer and cooked
>};
>  };
> 
>  const big = raw =>
>let in cooked = cook(raw), consume => {
>  // do things with consumer and cooked
>};
> 
> In short,
> 
>  let in binding = expr, stmt|expr
> 
> It may work for `const in` as well.
> 
> Herby
> 
> P.S.: Alternative syntax is "let a=3, b=4, ..., in foo(a,b,c,d)" but this can 
> only tell late if it is plain let-up-to-end-of-scope or local-scope-let, so 
> not sure if that may be a problem; OTOH you can chain more of them and 
> resembles classical let-in better.

Please, don’t take it too seriously: but have you thought about resuscitating 
the (in)famous `with` statement?

```js
const big = raw => 
do with ({cooked: cook(raw)})
consumer => {
// do things with consumer and cooked
};;
```

And no the two ”;”s are not a typo: I need to end both the `with` statement and 
the `const` declaration.

But more seriously... those sorts of “clever” syntaxes (`let-in` or `do-with` 
or whatever), apart from complicating the language, are in danger of raising as 
much issues than they’re resolving; the double-semicolon oddity is one of them.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: proposal: String.prototype.padCenter

2018-08-22 Thread Claude Pache
```js
x.padStart((x.length + 32)/2).padEnd(32)
```

(BTW, I don’t like this habit of top-posting the reply. Please look below for 
the question I’m answering, and read the mail backwards for more context.)

—Claude

> Le 22 août 2018 à 05:47, Naveen Chawla  a écrit :
> 
> How would you combine padStart and padEnd to get the desired result? Just 
> curious, because the idea would be to create a minimum of 32 chars with the 
> original string centered inside the "padding" (if there is any)
> 
> On Wed, 22 Aug 2018 at 07:26 Isiah Meadows  > wrote:
> What's wrong with combining `padStart` with `padEnd`? I'm not sure this is 
> worth it, since you can easily emulate it anyways (as you stated).
> On Tue, Aug 21, 2018 at 16:44 Ricardo Zorzal  > wrote:
> Hello guys, I here to talk about padStart, padEnd and my new proposal 
> "padCenter", I think it is not hard to develop because we already had 
> padStart and padEnd.
> 
> I thought that we need to add one more feature to String's prototype, and it 
> is not a hard work. So the proposal is to create the 
> String.prototype.padCenter that centralize a string with a max character 
> lenght, equals we do when call the "pad" functions.
> 
> For exemple, when we call padStart
> 
> ```javascript
> "MY-TEST".padStart(32)
> //result: " MY-TEST"
> ```
> 
> and when we call padEnd:
> 
> ```javascript
> "MY-TEST".padEnd(32)
> //result: "MY-TEST "
> ```
> 
> how about that:
> 
> ```javascript
> "MY-TEST".padCenter(32)
> //result: "MY-TEST"
> ```
> 
> I'm searching it for a long time and I seen people talking about it in 
> different use cases. But for me it will be usefull when I need to send some 
> text data to my bluetooth printer, becouse the length of his line is 32 and I 
> need to centralize the data and adjust the line to right and left.
> 
> I think this feature can improve the language and it will be useful for other 
> developers like me.
> 
> Although we has libs that has an implementation of it
> https://lodash.com/docs#pad 
> http://gabceb.github.io/underscore.string.site/#pad 
> 
> https://vocajs.com/#pad 
> I think it can be done for native functions too
> 
> And it is native for other languages, such as:
> 1. PHP 
> (https://www.w3schools.com/php/showphp.asp?filename=demo_func_string_str_pad3 
> )
> 2. Python (https://docs.python.org/2/library/string.html#string.center 
> )
> 3. Ruby (https://ruby-doc.org/core-2.2.0/String.html#center-method 
> )
> 4. R 
> (https://www.rdocumentation.org/packages/stringr/versions/1.3.1/topics/str_pad
>  
> )
> 5. etc...
> 
> 
> What do you guys think ?
> 
> ( We can call it "pad" instead of "padCenter"  haha )
> 
> 
> Att, 
> 
> Ricardo Zorzal Davila 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Implementing an identical JSON.stringify

2018-08-04 Thread Claude Pache


> Le 5 août 2018 à 05:07, Claude Pache  a écrit :
> 
> 
> 
>> Le 5 août 2018 à 04:50, Claude Pache > <mailto:claude.pa...@gmail.com>> a écrit :
>> 
>> 
>> 
>>> Le 5 août 2018 à 01:43, Michael Theriot >> <mailto:michael.lee.ther...@gmail.com>> a écrit :
>>> 
>>> Try `Number.prototype.valueOf.call(obj)`: it will throw a TypeError if and 
>>> only if `obj` has no [[NumberData]] internal slot. Ditto for String, 
>>> Boolean and Symbol.
>>> 
>>> I already mention this and demonstrate why it is not sufficient in my 
>>> example.
>>> 
>>> Reiterated plainly:
>>> ```js
>>> JSON.stringify(Reflect.construct(Number, [], Number)); // "0"
>>> JSON.stringify(Reflect.construct(Number, [], String)); // TypeError
>>> JSON.stringify(Reflect.construct(Number, [], Object)); // null
>>> ```
>> 
>> Per spec, the three expressions should produce `"0"`, as the three objects 
>> have a [[NumberData]] internal slot (step 4 of [1]). I guess there is some 
>> discrepancy between implementation and spec for those exotic edge cases?
>> 
>> [1]: https://tc39.github.io/ecma262/#sec-serializejsonproperty 
>> <https://tc39.github.io/ecma262/#sec-serializejsonproperty>
>> 
>> —Claude
>> 
> 
> I see that there is a difference in this algorithm between the current spec 
> and ES 2015 for that particular step. From my tests, current stable Firefox 
> and Safari (other browsers not tested) still follow the old algorithm.
> 
> —Claude
> 
> 
Nevrmind, forget the previous message. The algorithm does indeed somewhat 
strange here.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Implementing an identical JSON.stringify

2018-08-04 Thread Claude Pache


> Le 5 août 2018 à 04:50, Claude Pache  a écrit :
> 
> 
> 
>> Le 5 août 2018 à 01:43, Michael Theriot > <mailto:michael.lee.ther...@gmail.com>> a écrit :
>> 
>> Try `Number.prototype.valueOf.call(obj)`: it will throw a TypeError if and 
>> only if `obj` has no [[NumberData]] internal slot. Ditto for String, Boolean 
>> and Symbol.
>> 
>> I already mention this and demonstrate why it is not sufficient in my 
>> example.
>> 
>> Reiterated plainly:
>> ```js
>> JSON.stringify(Reflect.construct(Number, [], Number)); // "0"
>> JSON.stringify(Reflect.construct(Number, [], String)); // TypeError
>> JSON.stringify(Reflect.construct(Number, [], Object)); // null
>> ```
> 
> Per spec, the three expressions should produce `"0"`, as the three objects 
> have a [[NumberData]] internal slot (step 4 of [1]). I guess there is some 
> discrepancy between implementation and spec for those exotic edge cases?
> 
> [1]: https://tc39.github.io/ecma262/#sec-serializejsonproperty 
> <https://tc39.github.io/ecma262/#sec-serializejsonproperty>
> 
> —Claude
> 

I see that there is a difference in this algorithm between the current spec and 
ES 2015 for that particular step. From my tests, current stable Firefox and 
Safari (other browsers not tested) still follow the old algorithm.

—Claude


___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Implementing an identical JSON.stringify

2018-08-04 Thread Claude Pache


> Le 5 août 2018 à 01:43, Michael Theriot  a 
> écrit :
> 
> Try `Number.prototype.valueOf.call(obj)`: it will throw a TypeError if and 
> only if `obj` has no [[NumberData]] internal slot. Ditto for String, Boolean 
> and Symbol.
> 
> I already mention this and demonstrate why it is not sufficient in my example.
> 
> Reiterated plainly:
> ```js
> JSON.stringify(Reflect.construct(Number, [], Number)); // "0"
> JSON.stringify(Reflect.construct(Number, [], String)); // TypeError
> JSON.stringify(Reflect.construct(Number, [], Object)); // null
> ```

Per spec, the three expressions should produce `"0"`, as the three objects have 
a [[NumberData]] internal slot (step 4 of [1]). I guess there is some 
discrepancy between implementation and spec for those exotic edge cases?

[1]: https://tc39.github.io/ecma262/#sec-serializejsonproperty 


—Claude


___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Implementing an identical JSON.stringify

2018-08-04 Thread Claude Pache


> Le 5 août 2018 à 04:14, Darien Valentine  a écrit :
> 
> 
> However it is ultimately not possible to replicate because there is no 
> possible brand test for [[BooleanData]].

Per spec, checking whether `Boolean.prototype.valueOf.call(obj)` throws will 
test whether an object has [[BooleanData]] internal slot.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Implementing an identical JSON.stringify

2018-08-04 Thread Claude Pache


> Le 5 août 2018 à 00:16, Michael Theriot  a 
> écrit :
> 
> `JSON.stringify` has unintuitive behavior regarding interal slots.

I don’t think that anything involving an object that has a [[StringData]] 
internal slot but has `Number.prototype` in its prototype chain could have an 
”intuitive” behaviour...

> 
> 
> I think this is related to `Array.isArray`. Is there an equivalent 
> `Number.isNumber`? Or is this just something only `JSON.stringify` can do?

Try `Number.prototype.valueOf.call(obj)`: it will throw a TypeError if and only 
if `obj` has no [[NumberData]] internal slot. Ditto for String, Boolean and 
Symbol.

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Question: HTTPS everywhere...problem

2018-08-04 Thread Claude Pache

> Le 4 août 2018 à 22:22, Felipe Nascimento de Moura  a 
> écrit :
> 
> I know of (and I also support) the HTTPS everywhere campaign.
> 

I don’t think that ECMAScript has any feature related to the http protocol, or 
that make a distinction between secure and non-secure contexts. Wrong mailing 
list?

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: const {resolve} = Promise; // fails

2018-07-19 Thread Claude Pache


> Le 19 juil. 2018 à 16:32, Andrea Giammarchi  a 
> écrit :
> 
> I know it's about subclassing, which is why I've asked why, once there's no 
> context, the default/base one is not considered, but since everyone came back 
> with the subclassing issue, which is actually what I've said myself on 
> twitter about the current state, how about changing all public static methods 
> that need it, to be getters ?
> 
> ```js
> class Promise {
>   #resolve(...args) {
> return this.nativeImplementation(...args);
>   }
>   get resolve() {
> return #resolve.bind(this);
>   }
> }
> ```
> 
> we could argue `Promise.resolve === Promise.resolve` should be preserved, as 
> behavior, so that we need a lazy defined getter ... **but** why not making 
> public static restructuring from known constructors work regardless, under 
> all circumstances ?
> 

Nice hack... But it imposes all subclasses of `Promise` that override the 
`resolve` method to use a similar trick, because the following will break:

```js
class MyPromise extends Promise {
static resolve() {
// do fancy stuff
return super.resolve()
}
}

const {resolve} = MyPromise

resolve() // TypeError: undefined is not an object
```

Per the KISS principle, let’s avoid to be clever.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: const {resolve} = Promise; // fails

2018-07-19 Thread Claude Pache


> Le 19 juil. 2018 à 13:56, Andrea Giammarchi  a 
> écrit :
> 
> 
> Compared to every other public static method in ECMAScript that works, 
> including those methods that might need the contextual class, as it is for 
> the Array.from case.
> 
> ```js
> const {from} = Array;
> 
> from({0: 'abc', length: 1}); // ["abc"] // all good
> ```

That pattern falls apart when subclassing:

```js
class ImprovedArray extends Array {
/* implementation NOT overriding the `from` static method  */
}

const {from} = ImprovedArray

from({0: 'abc', length: 1}) // Array instance instead of ImprovedArray instance
```

So, no, the `Array.from` precedent is a bad one.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Static sort method on Array

2018-04-07 Thread Claude Pache


> Le 7 avr. 2018 à 21:59, Rob Ede  a écrit :
> 
> I don't like the fact the only way to sort is in-place with Array#sort and I 
> can't be the first to feel this way or wonder why there isn't a built-in 
> solution.
> 
> Obviously, searching "javascript array.sort" doesn't produce any helpful 
> results to see if someone has suggested this before since all the results 
> relate to Array#sort.
> 
> I'm considering creating a proposal to add an Array.sort() method that takes 
> an array and returns a new array. It seems like such a simple addition that 
> would remove the need to import lodash, write a helper function or use a 
> slightly less clear and possibly slower technique like `[...arr].sort()`.

`Array.from` (or indeed `[...arr]`) is a generic built-in way to create a new 
array, and is fine to use in every occasion where you need a copy. (Before ES6, 
there was already `arr.slice(0)`.) I don’t think it is appropriate to have an 
*additional* way to copy arrays for this specific case (it would be one more 
thing to learn). 

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Array.prototype.repeat

2018-03-25 Thread Claude Pache


> Le 25 mars 2018 à 20:27, Cyril Auburtin  a écrit :
> 
> String and Array share a few methods.
> 
> I think `repeat` could exist for Array as well
> 
> At the moment are other more verbose ways to do so:
> 
> - `Array.from({length: n}, () => 'foo')`
> - `Array(n).fill('foo')`
> - `[].concat(...Array.from({length: 3}, () => ['x', 'y']))`
> - `[].concat(...Array(3).fill(['x', 'y']))`
> 
> so with repeat it would just be;
> 
> - `['foo'].repeat(n)`
> - `['x', 'y'].repeat(3)`

For filling a new array with one value, `Array(n).fill('foo')` seems reasonable 
to me.

Are there use cases for filling with alternating values, as in `['x', 
'y'].repeat(3)`?

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Allow Object Destructoring when assigning

2018-03-22 Thread Claude Pache


> Le 22 mars 2018 à 20:51, Sebastian Malton  a écrit :
> 
> Currently object destructoring is only allowed during variable declaration, 
> however it would be useful, and seems rather odd from a usage standpoint, 
> that it cannot be done during assignment. 
> 
> Example:
> This is a allowed:
> ```
> const { a } = b;
> ```
> 
> But this is not:
> ```
> let a;
> 
> if (...) {
> { a } = b.c;
> }
> ```
> 
> Sebastian Malton
> 

This is already allowed, but you have to use some artefact in order to force 
the parser not to interpret`{` as the beginning of a block:

```
let a ;
({ a } = b);
```

—Claude 

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: add reverse() method to strings

2018-03-19 Thread Claude Pache


> 
> The only reason I would defend the "reverse" method in strings is because it 
> makes sense.
> I think JavaScript is very intuitive, and, as Arrays do have the "reverse" 
> method, that simply makes sense to have it in strings as well.
> 

”Making sense” and ”symmetry of API” is not a sufficient reason, because a 
string is not ”just” an immutable array of chars. Consider:

1. Some methods defined on arrays only: `find`, `reduce`, `reverse`
2. Some methods defined on strings only: `repeat`, `startsWith`
3. Some methods defined on both arrays and strings with same semantics: 
`concat`, `slice`
4. Some methods defined on both arrays and strings with different semantics: 
`includes`, `indexOf`

Existence of methods listed in (1), (2) and (4) is a consequence of strings and 
arrays having different needs.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: add reverse() method to strings

2018-03-17 Thread Claude Pache


> Le 17 mars 2018 à 19:29, Oriol _  a écrit :
> 
> Be aware your code breaks pair surrogates, which might be undesirable:
> 
> ```js
> var str = "a_\uD83D\uDE80_b";
> str.split("").reverse().join(""); // "b_\uDE80\uD83D_a" :(
> [...str].reverse().join("");  // "b_\uD83D\uDE80_a" :)
> ```
> 
> —Oriol

Well, but be aware that the corrected implementation still breaks graphemes 
composed by a sequence of code points, such as: n̈ ( LATIN SMALL LETTER N + 
COMBINING DIEARESIS), which might be undesirable...

Anyway, what are the use cases?

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: try/catch/else

2018-02-09 Thread Claude Pache


> Le 9 févr. 2018 à 00:19, Peter van der Zee <e...@qfox.nl> a écrit :
> 
>>> On Thu, Feb 8, 2018 at 10:13 AM, Claude Pache <claude.pa...@gmail.com>
>>> wrote:
>>>> 
>>>> What about the following pattern (labelled block + break)?
>>>> 
>>>> ```js
>>>> processSuggestions: {
>>>>let suggestions;
>>>>try {
>>>>  suggestions = await fetchSuggestions();
>>>>} catch (e) {
>>>>  alert('Failed to load suggestions');
>>>>  break processSuggestions;
>>>>}
>>>>showSuggestions(suggestions);
>>>> }
>>>> ```
> 
> I don't mean to hijack this tread. I'm mostly curious why you opt or
> even suggest for that over putting it in a function and an early
> return? Like;
> 
> ```
> function processSuggestions() {
>  let suggestions
>  try {
>suggestions = await fetchSuggestions();
>  } catch (e) {
>return alert('Failed to load suggestions');
>  }
>  showSuggestions(suggestions);
> }
> ```
> 
> This is almost identical, especially the way the example was written.
> I understand the differences, I don't think they're a problem for by
> far most cases where you'd want this.

A function is strictly more complex than a block because you have to define it 
first, then to invoke it. As a consequence, it is more code to write and read. 
Unless you have a good reason for it (which is not suggested by the original 
problem), why would you prefer the more complex way?

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: try/catch/else

2018-02-08 Thread Claude Pache
What about the following pattern (labelled block + break)?

```js
processSuggestions: {
let suggestions;
try {
  suggestions = await fetchSuggestions();
} catch (e) {
  alert('Failed to load suggestions');
  break processSuggestions;
}
showSuggestions(suggestions);
}
```

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: ASI edits

2018-01-14 Thread Claude Pache


> Le 14 janv. 2018 à 03:31, Isiah Meadows <isiahmead...@gmail.com> a écrit :
> 
> Inline
> -
> 
> Isiah Meadows
> m...@isiahmeadows.com <mailto:m...@isiahmeadows.com>
> 
> Looking for web consulting? Or a new website?
> Send me an email and we can get started.
> www.isiahmeadows.com <http://www.isiahmeadows.com/>
> 
> 
> On Sat, Jan 13, 2018 at 9:54 AM, Claude Pache <claude.pa...@gmail.com 
> <mailto:claude.pa...@gmail.com>> wrote:
>> 
>> 
>> Le 12 janv. 2018 à 22:09, Isiah Meadows <isiahmead...@gmail.com> a écrit :
>> 
>> I know this is probably bad timing (considering [this PR][1] and the
>> fallout that followed), but I was thinking that it'd be nice if we
>> could insert a `[no LineTerminator here]` clause in a few places, to
>> remove some of the ASI hazards for those going semicolon-free, along
>> with some extras for consistency:
>> 
>> - Before the `[` in the second rule of [`MemberExpression`][2] and the
>> fourth rule of [`CallExpression`][3]
>> - Before `Arguments` in the last rule of [`MemberExpression`][2], the
>> third and sixth rule of [`CallExpression`][3], and
>> [`CoverCallExpressionAndAsyncArrowHead`][4]
>> - Before the `(` in [`FunctionDeclaration`][5],
>> [`FunctionExpression`][6], the first, fourth, and fifth rule of
>> [`MethodDefinition`][7], [`GeneratorMethod`][8], both rules in
>> [`GeneratorDeclaration`][9], and [`GeneratorFunction`][10]
>> 
>> One of the practical effects would be this: this source (taken from the
>> spec):
>> 
>> ```js
>> a = b + c
>> (d + e).print()
>> ```
>> 
>> is currently interpreted as:
>> 
>> ```js
>> a = b + c(d + e).print();
>> ```
>> 
>> but would, with this proposal, be interpreted as this, which is a
>> *lot* more intuitive with what people would expect:
>> 
>> ```js
>> a = b + c;
>> (d + e).print();
>> ```
>> 
>> I know there's risk of web compat concerns, but I doubt they'd be
>> significant for anything that's not minified via the Closure Compiler
>> (which limits line length by default for reasons of old IE). Also, for
>> most non-ASI people, they probably just forgot a semicolon anyways,
>> and [here][11] is a concrete example of this, where ESLint was fixing
>> a linter violation incorrectly because it wasn't reading it as you'd
>> expect.
>> 
>> 
>> I think that the BC incompatibility issue is more than just a risk. I recall
>> (but I couldn’t find it) that someone gave the example of some library that
>> reads better when used as:
>> 
>> ```js
>> foo
>>  (bar)
>>  (baz)
>> ```
> 
> Do you have any ideas where I could look to potentially find it? I've
> never seen *that* kind of DSL before, and that's an interesting use
> case I haven't considered.

I’ve finally found, see:
https://esdiscuss.org/topic/consider-adding-more-no-lineterminator-here-to-avoid-problem-caused-by-omit-the-semicolon#content-3
 
<https://esdiscuss.org/topic/consider-adding-more-no-lineterminator-here-to-avoid-problem-caused-by-omit-the-semicolon#content-3>

Maybe not a significant example, but don’t underestimate the creativity of 
hackers.

> 
>> 
>> Also, cases you have forgotten, and where I *really* wish there be a [NLTH]
>> rule, are *after* some contextual keywords that are used in prefix position,
>> namely `get`, `set` and `static` (as it is already the case for `async`).
>> See
>> https://tc39.github.io/proposal-class-fields/#sec-asi-hazards-in-class-bodies
>>  
>> <https://tc39.github.io/proposal-class-fields/#sec-asi-hazards-in-class-bodies>
>> for context. This is not only to satisfy my coding style, but also to ensure
>> consistency when further contextual keywords will be added in the top level
>> of class bodies, since those future keyword will require such a [NLTH] rule
>> in order to be compatible with previously written field declarations that
>> take advantage ASI.
> 
> I thought about those, and I would ideally like those to be similarly
> chnaged, but I decided against including them in this particular
> proposal, since I wanted to focus on `[` and `(`, and I wasn't as keen
> on web compat (considering it's actually a style many people prefer).

As someone who uses semicolon-less style, `[`, `(` and other punctuation marks 
are not issues, but `get`, `set` and `static` in class fields are. My analysis:
https://github.com/tc39/proposal-class-fields/issues/7#issuecomment-331670382 
<https://github.com/tc39/proposal-class-fields/issues/7#issuecomment-331670382>

But regardless of your c

Re: ASI edits

2018-01-13 Thread Claude Pache


> Le 12 janv. 2018 à 22:09, Isiah Meadows  a écrit :
> 
> I know this is probably bad timing (considering [this PR][1] and the
> fallout that followed), but I was thinking that it'd be nice if we
> could insert a `[no LineTerminator here]` clause in a few places, to
> remove some of the ASI hazards for those going semicolon-free, along
> with some extras for consistency:
> 
> - Before the `[` in the second rule of [`MemberExpression`][2] and the
> fourth rule of [`CallExpression`][3]
> - Before `Arguments` in the last rule of [`MemberExpression`][2], the
> third and sixth rule of [`CallExpression`][3], and
> [`CoverCallExpressionAndAsyncArrowHead`][4]
> - Before the `(` in [`FunctionDeclaration`][5],
> [`FunctionExpression`][6], the first, fourth, and fifth rule of
> [`MethodDefinition`][7], [`GeneratorMethod`][8], both rules in
> [`GeneratorDeclaration`][9], and [`GeneratorFunction`][10]
> 
> One of the practical effects would be this: this source (taken from the spec):
> 
> ```js
> a = b + c
> (d + e).print()
> ```
> 
> is currently interpreted as:
> 
> ```js
> a = b + c(d + e).print();
> ```
> 
> but would, with this proposal, be interpreted as this, which is a
> *lot* more intuitive with what people would expect:
> 
> ```js
> a = b + c;
> (d + e).print();
> ```
> 
> I know there's risk of web compat concerns, but I doubt they'd be
> significant for anything that's not minified via the Closure Compiler
> (which limits line length by default for reasons of old IE). Also, for
> most non-ASI people, they probably just forgot a semicolon anyways,
> and [here][11] is a concrete example of this, where ESLint was fixing
> a linter violation incorrectly because it wasn't reading it as you'd
> expect.

I think that the BC incompatibility issue is more than just a risk. I recall 
(but I couldn’t find it) that someone gave the example of some library that 
reads better when used as:

```js
foo
  (bar)
  (baz)
```

Also, cases you have forgotten, and where I *really* wish there be a [NLTH] 
rule, are *after* some contextual keywords that are used in prefix position, 
namely `get`, `set` and `static` (as it is already the case for `async`). See 
https://tc39.github.io/proposal-class-fields/#sec-asi-hazards-in-class-bodies 
 
for context. This is not only to satisfy my coding style, but also to ensure 
consistency when further contextual keywords will be added in the top level of 
class bodies, since those future keyword will require such a [NLTH] rule in 
order to be compatible with previously written field declarations that take 
advantage ASI.

—Claude



> 
> [1]: https://github.com/tc39/ecma262/pull/1062
> [2]: https://tc39.github.io/ecma262/#prod-MemberExpression
> [3]: https://tc39.github.io/ecma262/#prod-CallExpression
> [4]: https://tc39.github.io/ecma262/#prod-CoverCallExpressionAndAsyncArrowHead
> [5]: https://tc39.github.io/ecma262/#prod-FunctionDeclaration
> [6]: https://tc39.github.io/ecma262/#prod-FunctionExpression
> [7]: https://tc39.github.io/ecma262/#prod-MethodDefinition
> [8]: https://tc39.github.io/ecma262/#prod-GeneratorMethod
> [9]: https://tc39.github.io/ecma262/#prod-GeneratorDeclaration
> [10]: https://tc39.github.io/ecma262/#prod-GeneratorExpression
> [11]: https://github.com/eslint/eslint/issues/7787
> 
> -
> 
> Isiah Meadows
> m...@isiahmeadows.com
> 
> Looking for web consulting? Or a new website?
> Send me an email and we can get started.
> www.isiahmeadows.com
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Looking for Champion: Null Coalescing (??) and Null Conditional Member Access (?.) operators

2017-12-20 Thread Claude Pache
There are already official proposals for those. See:

https://github.com/tc39/proposals 

and search for “Nullish coalescing Operator” for the first of your suggestions 
and “Optional Chaining” for the second one.

—Claude



> Le 20 déc. 2017 à 09:03, Arash Motamedi  a écrit :
> 
> I’d like to propose two new operators that I’ve appreciated using in C#, with 
> appropriate modifications for Ecmascript. 
> 
> ?? Null-Coalescing Operator
> 
> The ?? operator is called the null-coalescing operator. It returns the 
> left-hand operand if the operand is not null or undefined; otherwise it 
> returns the right hand operand. (modified excerpt from C# definition, here 
> .)
>   
> 
> Examples:
>  
> let u = undefined;
> let nu = u ?? 0; 
> //  nu = (u !== undefined && u !== null) ? u : 0
> 
> let n = null;
> let nn = n ?? "Default"; 
> //  nn = (n !== undefined && n !== null) ? n : "Default";
> 
> let p = someObj.someProp ?? "Hello"; 
> //  p = (someObj.someProp !== undefined && someObj.someProp !== null) ? 
> someObj.someProp : "Hello";
> 
> The ?? operator allows for a very terse syntactic representation of a rather 
> common statement, and its value becomes very clear when evaluating and 
> accessing properties on objects, as illustrated in the 3rd example above. For 
> credit, comparison, and further details, please review the C# null coalescing 
> operator information here 
> .
>  
> 
> 
> ?. Null Conditional Member Access and ?[ Null Conditional Index Access
> 
> Used to test for null or undefined before performing a member access (?.) or 
> index (?[) operation. (modified excerpt from C# definition here 
> .)
>  
> 
> Examples:
>  
> let n = null;
> let nn = n?.name; 
> //  nn = (n.name  !== null && u.name  !== 
> undefined) ? u.name  : u.name ;
> 
> let p = {name: "John"};
> let l = p.lastName?.length; 
> //  l = (u.lastName !== null && u.lastName !== undefined) ? u.lastName.length 
> : u.lastName;
> 
> The ?. and ?[ operators allow for graceful access (as opposed to 
> null/undefined reference errors) to object members, and are particularly 
> useful when used in a chained manner. For credit, comparison, and further 
> details, please review the C# null conditional member access operator 
> information here 
> .
>  
> 
> 
> Combining the above operators can enable very concise syntax for checking 
> against null/undefined and providing default values in a graceful manner. 
> 
> let lastNameLength = person.lastName?.length ?? 0; 
> let cityToUppercase = person.address?.city?.toUpperCase() ?? "N/A"; 
> 
> 
> Looking forward to working with the community and hopefully bringing these 
> two operators to the language. 
> 
> Best,
> Arash
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Allow any quoted string to be multiline?

2017-12-18 Thread Claude Pache


> Le 17 déc. 2017 à 22:03, J Decker  a écrit :
> 
> I do see there are work-arounds (similar as using a hammer to put in a screw)
> 
> I don't see a reason for why not allow multiline strings for other quote 
> types.  I know... because people want more errors and to have their hand held 
> to identify missing close quotes?  much like the desire to add types and type 
> checking.

Yes, you gave a valid reason just after having said you didn’t see a reason: 
transforming bugs (missing quote) into early errors, so that it is easier to 
debug...

The obvious workaround, i.e. using a template literal without placeholder, 
doesn’t seems too heavy-weight; on the contrary, it is probably the lightest 
one can imagine.

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: es-discuss Digest, Vol 130, Issue 41

2017-12-16 Thread Claude Pache

> Le 16 déc. 2017 à 07:10, zhaoshche  a écrit :
> 
> Who can tell me what is it?
> Why always send to me?
> How to undescribe it?


Your e-mail address is most probably subscribed to the es-discuss mailing list. 
Instructions to unsubscribe is found at the bottom of this page:

https://mail.mozilla.org/listinfo/es-discuss

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Make comma at the end of line optional

2017-09-12 Thread Claude Pache

> Le 12 sept. 2017 à 18:57, Алексей  a écrit :
> 
> Don't you think that line break is a strong punctuation by itself?

It could have been. Unfortunately, in JS, it is not.

Automatic semi-colon insertion (ASI) could be seen as an attempt to have their 
cake and eat it too. Or, as a compromise between the two options by making 
*some* line breaks significant (e.g., the one after `return`).

But in general, line breaks are not significant enough to allow to introduce 
ASI-like rules after the fact, that would work reliably enough.

BTW, the title of the thread, “Make comma at the end of line optional”, reveals 
a probable misunderstanding of the feature. In JS, semicolons are not 
“optional”, they are “automatically inserted”. That makes a difference when 
parsing:

```js
a = b
+c
```


—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Make comma at the end of line optional

2017-09-12 Thread Claude Pache

> Le 12 sept. 2017 à 18:00, Алексей  a écrit :
> 
> Sorry, but I don't see any problems with example you provide:
> 
> const object = {
>   get // not a complete declaration statement - so no implicit comma here
>   y: 2 // continuation of a previous line
> 
>   z: x // complete declaration statement and next line is not an operator - 
> implicit comma here
>   in: "foo"
> }


This is not how ASI works. A implicit semicolon is not added when a declaration 
would be complete, but when the next token would produce a syntax error. —Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Make comma at the end of line optional

2017-09-12 Thread Claude Pache
There are [no LineTerminator here] rules in the ES grammar, in order to prevent 
the most pernicious trap when using ASI:

```
return // implicit semicolon here
a = b
```

Those [no LineTerminator here] rules have not been included in constructs that 
don’t need them. As a result:

```
const object = {
get // no implicit comma here
y: 2

z: x // no implicit comma here
in: "foo"
}
```

So, no, it’s not a good idea.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Native Function Composition

2017-08-25 Thread Claude Pache

> Le 24 août 2017 à 23:13, Naveen Chawla  a écrit :
> 
> That's a syntax for calling functions, not creating a composed function for 
> being called any time.
> 
> Personally I don't find that proposal compelling because I don't think it 
> saves much code vs current syntax - it only straightens the order and 
> replaces () with using |>.

Straightening the order is still a big deal in lengthy expressions. And 
imbalance of nesting parentheses is one of my main sources of syntax errors. 

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposing a conditional assignment (or equals) operator

2017-08-15 Thread Claude Pache
This feature is more related to null coalescing (evaluate the RHS when the LHS 
is null) than to optional chaining (evaluate the LHS when the LHS is *not* 
null).

See https://github.com/gisenberg/proposal-nullary-coalescing/issues/1 


—Claude

> Le 15 août 2017 à 03:11, Ari Porad  a écrit :
> 
> Hi All,
> 
> Given that optional chaining is now stage–1, would there be interest in 
> reviving this proposal? (This idea originated from my comment here 
> .)
> 
> Apologies if this isn’t the proper way to suggest this idea, it’s my first 
> time posting on es-discuss!
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: an operator for ignoring any exceptions

2017-08-14 Thread Claude Pache
Note that, in a try/catch/finally construct, you can already omit the catch 
clause if there is a finally clause. The effect, of course, is not to swallow 
the exception, but, on the contrary, to propagate it as if there was `catch (e) 
{ throw e }`. (The useful part of such a construct is the finally clause.)

Also, in languages and dialects supporting conditional catch clauses, if the 
thrown exception does not match the condition of any catch clause, it is 
propagated.

So, the rule is: If there a matching catch clause, the exception is handled by 
it; otherwise, it is propagated. Reversing that rule (“propagated” → “not 
propagated”) is very dubious, to start (regardless of any other consideration).

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Migrating to a better communication tool

2017-07-25 Thread Claude Pache
Previous discussion:

https://esdiscuss.org/topic/move-es-discuss-to-discuss-webplatform-org

—Claude 

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Spaceship Operator

2017-06-28 Thread Claude Pache

> Le 27 juin 2017 à 22:19, Mike Samuel  a écrit :
> 
> On Tue, Jun 27, 2017 at 4:13 PM, Isiah Meadows  wrote:
>> For what it's worth, for most practical purposes, `arr.sort((a, b) => b -
>> a))` works well enough. (The only thing it doesn't work well with are NaNs,
>> but in practice, those almost never occur.)
> 
> Don't numeric comparison operators typically sort -0 before +0?
> 
> ((a,b)=>b-a) is also problematic for an array that contains two or
> more infinite values with the same sign and one or more finite values
> since isNaN(Infinity-Infinity).   That NaN from the comparator can be
> triggered or not based on details of the sorting algo and the precise
> placement on the Infinities.

When the comparison function produces NaN, it is treated the same way as 0; so 
no it is not a problem for infinities.
More precisely, because `(Infinity - Infinity)` is NaN,  `Infinity` is treated 
as “equal” to `Infinity`, which is correct.

It is an issue with `NaN`, because `NaN` will be treated as “equal” to any 
value.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Arrow function followed by divide or syntax error?

2017-05-23 Thread Claude Pache
> Le 23 mai 2017 à 16:34, Gareth Heyes  a écrit :
> 
> Hi all
> 
> I'd like to discuss this:-
> 
> x=x=>{}/alert(1)/+alert(2)// alerts on edge, syntax error on other browsers
> 
> So on Edge it results in two alerts but every other browser it's a syntax 
> error. Personally I think Edge is right here because it's a function 
> expression so why can't you use divide after.

This is not specific to the divide operator. If you try:

```js
x => {} * alert(1)
```

you'll get a SyntaxError in all browsers but Edge, which interprets it as `(x 
=> {}) * alert(1)`.

Given how confusing that expression is, I think that the SyntaxError is the 
right choice.

> 
> x=>{}
> /alert(1)/+alert(2)//alerts twice on edge, once on other browsers

This follows from the ASI rules: non-Edge browsers add a missing semicolon 
between the two lines, because otherwise it would be a syntax error for them.

—Claude

> 
> Cheers
> Gareth
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: {this} object literal

2017-04-21 Thread Claude Pache

More generally, all keywords are excluded, that makes sense in general as, 
e.g., `{ if }` could not be equivalent to `{ if: if }`, or `{ yield }` inside a 
generator function should not be equivalent to `{ yield: yield }`.

But yes, one could have special-cases for literals such as `this`, `true`, 
`false` and `null`. It is an accident of history that `{ NaN }` and `{ 
undefined }` work as expected, but not `{ null }`.

—Claude

> Le 21 avr. 2017 à 19:01, Michał Wadas  a écrit :
> 
> Hi.
> 
> Is there any specific reason why {this} literal is forbidden? Babel had a bug 
> allowing this and it was pretty convenient to enter console.log({this, 
> arguments, externalVar}) for quick printing scope.
> 
> Michał Wadas
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Strict (non-coercing) expressions

2017-04-17 Thread Claude Pache

> Le 13 avr. 2017 à 08:39, T.J. Crowder  a 
> écrit :
> 
> In the thread on [strict relational operators][1], felix [suggested][2] an 
> expression mode affecting all operators:
> 
> > Maybe every operator can have a non-coercing variant?
> >
> > One possible syntax is to have a modifier on operators
> >
> >x = a (<) b (+) c (&&) (!)d;
> >
> >if (x (!=) y) ...
> >
> >
> > Another possible syntax is to have a modifier on expressions
> >
> >x = #(a < b + c && !d)
> >
> >if #(x != y) ...
> 
> I though the idea deserved its own thread. It's much broader in scope than 
> strict relational operators, and not exclusive with them.
> 

I think that, in general, “implicit coercion” is not the real issue, although 
it makes things worse in some cases. The real issue is “ambivalent meaning”.

For example, `+` is so problematic in JS because it has two contradictory 
meanings: addition and concatenation.

On the other hand, `<` is less problematic, because there is much rarely a 
situation where it is ambiguous (for a human).

Another example:

```js
var a = new Date
var b = new Date(a)
a <= b // true
a < b // false
a == b // probably not what you mean
```

In this case, “stricter” is not helpful in the “equality” test. What would have 
helped, is comparison operators with non-ambivalent meanings.  E.g., Perl has 
`==` for numerical comparison, `eq` for string comparison, and, since v6, `eqv` 
for structural comparison, `===` for identity comparison, `=:=` for...

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: new [[HasProperty]] invariant for non-extensible objects

2017-03-06 Thread Claude Pache

> Le 6 mars 2017 à 11:10, Raul-Sebastian Mihăilă  a 
> écrit :
> 
> To be more explicit, the invariants allow this surprising behavior:
> 
> ```js
> Object.preventExtensions(nonStandardExoticObject);
> Object.isExtensible(nonStandardExoticObject); // false
> 
> 'foo' in nonStandardExoticObject; // false
> 
> Object.getOwnPropertyDescriptor(nonStandardExoticObject, 'foo'); // {value: 
> 2, enumerable: true, configurable: true, writable: true}
> ```

That particular case should be covered by the following items in section 
[Invariants of the Essential Internal Methods] 
(https://tc39.github.io/ecma262/#sec-object-internal-methods-and-internal-slots)

Definitions:
A non-existent property is a property that does not exist as an 
own property on a non-extensible target.

And:

[[GetOwnProperty]] (P)
(last item): If the target is non-extensible and P is 
non-existent, then all future calls to [[GetOwnProperty]] (P) on the target 
must describe P as non-existent (i.e. [[GetOwnProperty]] (P) must return 
undefined).

However, it is true that the definition of “non-existent” property is at best 
vague, at worst incomplete. That is, instead of “does not exist as an own 
property”, it should say that one of the three following things happens, all of 
them are intuitively interpreted as implying that there does not exist an own 
property named P:

* [[GetOwnProperty]](P) returns undefined, or
* [[HasProperty]](P) returns false, or
* [[OwnPropertyKeys]]() returns a List that doesn't include P.

That said, there are other (often subtle) issues in that section. Few months 
ago, I have attempted a more rigorous reformulation; the motivation at that 
time was to check whether the integrity checks for Proxies were complete:

https://github.com/claudepache/es-invariants/blob/master/invariants.md 


In that document the notion of “non-existent property” (implied: on a 
non-extensible object) is translated into the lock: @exists(P): false.

However, I don’t consider it as a pressing issue, because the spirit of the 
section Invariants of the Essential Internal Methods seems correct, even if the 
letter is provably incomplete or vague.

—Claude



___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: a more consistent and stricter number converting function - Number.of()

2017-02-24 Thread Claude Pache

> Le 24 févr. 2017 à 04:50, 段垚  a écrit :
> 
> Hi,
> 
> 
> Converting an arbitray value to a number in JS can be rather inconsistent and 
> unexpected:
> 
> * `null` and `undefined` are different: `+null === 0` but `+undefined` is NaN.
> 
> * Empty string and non-nubmeric strings are different: `+"" === 0` but 
> `+"foo"` is NaN.
> 
> 
> This problem can be worse because JSON only support finite numbers:
> 
> ```
> 
> var total = 0;
> 
> total += JSON.parse(JSON.stringify({ "value": 0/0 })).value;
> 
> total === 0; //Oops, NaN is serialized as null, and then converted to 0
> 
> ```
> 
> So I propose a more consistent and stricter number converting function: 
> `Number.of(value)`:
> 
> 1. If `value` is `null` or `undefined`, return `NaN`;
> 
> 2. If `value` is a number, return `value` itself;
> 
> 3. If `value.valueOf()` returns a number, return that number, otherwise 
> return `NaN`.
> 
> 
> This means all non-number values except those have number type `.valueOf()` 
> would be converted to NaN:
> 
> 
> ```
> 
> Number.of(null); // NaN
> 
> Number.of(''); //NaN
> 
> Number.of('1'); //NaN
> 
> 
> var total = 0;
> 
> total += Number.of(JSON.parse(JSON.stringify({ "value": 0/0 })).value);
> 
> total; // NaN
> 
> ```
> 
> 
> What do you think?
> 
> 
> Regards,
> 
> Duan, Yao
> 


Depending on the concrete situation, you might not need yet another way to 
convert into number.

* If you know that your input is either a string or null/undefined (e.g., as 
the result of  `someHTMLElement.getAttribute('foo')`), you could use 
`Number.parseFloat()`, which will produce NaN for the empty string, null and 
undefined.

* If your issue is precisely with null/undefined, as it is the case in your 
JSON example, a more generic solution would be the null-coalescing operator 
`??`, which allows to express more precisely and more clearly what you mean. 
The semantics is:

```js
a ?? b // evaluates `a`. If `a` is null or undefined, evaluates `b`.
```

In your JSON example:

```js
var total = 0;

total += JSON.parse(JSON.stringify({ "value": 0/0 })).value ?? NaN;

Number.isNaN(total); // true. Hurray!
```

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Or Equal Operator

2017-02-03 Thread Claude Pache

> Le 4 févr. 2017 à 02:12, Артем Гуржий  a écrit :
> 
> Hi, I was thinking, is there a proposal for `or equal` operator as in ruby, 
> or is there any sense for doing so?
> Example:
> ```js
> let a = 1;
> let b = 0;
> a ||= b;
> ```
> Would be interpreted as
> ```js
> a = a || b;
> ```
> PS:
> Ruby version is
> ```ruby
> a || a = b;
> ```
> They are both equal, but it doesn't look like the javascript version of doing 
> this.

Older discussions on the topic: 

https://esdiscuss.org/topic/proposing-a-conditional-assignment-or-equals-operator
 

https://esdiscuss.org/topic/new-assignment-operators-not-bit-wise-or 

https://esdiscuss.org/topic/please-add-orequal-operator 

https://esdiscuss.org/topic/is-much-needed 

https://esdiscuss.org/topic/operators-and 

https://esdiscuss.org/topic/logical-assignment-operators 


—Claude


___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Short Comparing proposal

2017-02-03 Thread Claude Pache

> Le 3 févr. 2017 à 21:05, Bob Myers  a écrit :
> 
> If you're worried about short-circuiting, then
> 
> ```
> [() => a, () => b].some(x => c === x())
> ```

Even shorter: `(_ => _ === a || _ === b )(c)`

But more seriously: Now you have another issue, namely readability.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Determining if an object can be constructed

2017-01-19 Thread Claude Pache

> Le 19 janv. 2017 à 13:46, Andrea Giammarchi  a 
> écrit :
> 
> If you are looking for isClass or similar you can also rely on 
> `Function.prototype.toString` decompilation, which is de facto consistent.
> 
> ```js
> const isClass = (fn) =>
>   typeof fn === 'function' &&
>   !isClass.toString.call(fn).indexOf('class ');
> ```
> 
> Of course if you transpile code, including classes, that'd be useless (but 
> then you'll have many other problems anyway)

It is also useless when `Function#toString()` is not correctly implemented, 
which is currently the case for Firefox, see: 
https://bugzilla.mozilla.org/show_bug.cgi?id=1216630 


—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Determining if an object can be constructed

2017-01-19 Thread Claude Pache

> Le 19 janv. 2017 à 13:18, Isiah Meadows <isiahmead...@gmail.com> a écrit :
> 
> Inline.
> 
> On Thu, Jan 19, 2017, 03:26 Claude Pache <claude.pa...@gmail.com 
> <mailto:claude.pa...@gmail.com>> wrote:
>> Le 17 janv. 2017 à 23:48, Isiah Meadows <isiahmead...@gmail.com 
>> <mailto:isiahmead...@gmail.com>> a écrit :
>> 
>> Out of curiosity, why are classes specified to have a [[Call]] internal 
>> method instead of special-casing `typeof` and friends to work with them? 
>> Somewhat of a tangent, but just a curious question on the design decision.
>> 
> 
> I guess that class constructors could have been specified without a [[Call]] 
> internal method, with the cost of amending all the places where 
> “constructible” implicitly implies “callable”.
> 
> FWIW, calling methods that don't have [[Call]] already throws a TypeError. So 
> it wouldn't affect necessarily all sites, especially if you continue to check 
> for [[Call]] in `Array.prototype.forEach` (like what is currently done), etc.
> 
> But why (and how) do you need “special-casing `typeof` and friends”? (The way 
> the question is formulated, avoiding special-casing would be an argument for 
> the current design. But I miss what are the special cases you have in mind, 
> especially regarding `typeof`.)
> 
> I was specifically referring to `typeof (class {}) === "function"`. The "and 
> friends" was in reference to things like the callback in 
> `Array.prototype.forEach`, which IIUC doesn't currently throw for classes if 
> the array has no members.

If you intend to have no observable difference, I don’t see the point to spec 
it another way just for introducing special cases here and there.

About typeof. If you insist that a class has no [[Call]] internal method, I 
think that `typeof class {}` must *not* be `"function"`. I have heard 
complaints that classes look like callable objects, but are not usable as 
callable objects in practice. It would not be nice to maintain that gotcha by 
an explicit special case.

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Determining if an object can be constructed

2017-01-19 Thread Claude Pache

> Le 17 janv. 2017 à 23:48, Isiah Meadows  a écrit :
> 
> Out of curiosity, why are classes specified to have a [[Call]] internal 
> method instead of special-casing `typeof` and friends to work with them? 
> Somewhat of a tangent, but just a curious question on the design decision.
> 
I guess that class constructors could have been specified without a [[Call]] 
internal method, with the cost of amending all the places where “constructible” 
implicitly implies “callable”. But why (and how) do you need “special-casing 
`typeof` and friends”? (The way the question is formulated, avoiding 
special-casing would be an argument for the current design. But I miss what are 
the special cases you have in mind, especially regarding `typeof`.)

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Determining if an object can be constructed

2017-01-18 Thread Claude Pache

> Le 17 janv. 2017 à 23:56, Oriol _  a écrit :
> 
> See my 
> http://stackoverflow.com/questions/39334278/check-if-object-is-a-constructor-isconstructor
>  
> 
> 
> I also thought the `extends` trick could be useful, but it fails 3 of my 
> tests. It doesn't work for bounded normal functions and some proxy objects.

Yes, I missed the fact that subclassing implies a concrete access to the 
`prototype` property of the superclass in order to construct the subclass' 
prototype. That is the root of the failures.

> 
> The proper way is the second one in Claude's post: using a proxy object.
> 
> There is only a problem: it doesn't work for revoked proxies, because they 
> can't be used as a proxy target.
> 
> In my opinion that restriction is somewhat stupid, because you can use a 
> revocable proxy as a proxy target, and revoke it later.
> 
> But I guess it's too late to change that.

It is not too late to change that point, in that the risk of breakage may 
reasonably be judged almost inexistant. The hard part is to convince people 
that the inability to use a revoked proxy as proxy target is troublesome enough 
in order to justify the change. (Also, knowing why there is such a restriction 
may help to judge.)


> Maybe some day we will have `Object.isConstructor`.
> 
> ;Oriol
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Determining if an object can be constructed

2017-01-17 Thread Claude Pache

> Le 16 janv. 2017 à 18:00, Michael Haufe  a écrit :
> 
> The question came up recently on CLJS [1] on how to determine if an object is 
> safe to call as a Constructor.

The two following procedures will determine whether an object is a constructor 
without running it, according to ES6. (Whether it is safe to call it as 
constructor... you need first a definition of "safe".)

(1) Using `class/extends`:

```js
function isConstructor1(f) {
if (f === null)
return false
try {
class c extends f { }
return true
}
catch (e) {
   return false
}
}
```

(2) Using `Proxy`:

```js
function isConstructor2(f) {
var p = new Proxy(f, { construct() { return {} } })
try {
new p
return true
}
catch (e) {
   return false
}
}
```


—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Destructuring object outside of var declaration

2016-11-15 Thread Claude Pache


> Le 14 nov. 2016 à 22:53, Boris Zbarsky  a écrit :
> 
>> On 11/13/16 1:28 PM, Thaddee Tyl wrote:
>>var foo, bar;
>>{foo, bar} = {foo: 2, bar: 3};
>> 
>> is a "SyntaxError: expected expression, got '='" in Firefox, and *it
>> works in Google Chrome*.
> 
> I get "Uncaught SyntaxError: Unexpected token =" in Chrome "56.0.2914.3 dev" 
> and in Chrome "54.0.2840.9" (release).
> 
> -Boris

My guess is that Thaddee Tyl was confused by a Chrome DevTools feature, as in:

https://esdiscuss.org/topic/incosistency#content-6

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Wrapping regex's with proxies isn't working

2016-11-10 Thread Claude Pache

> Le 10 nov. 2016 à 15:50, Isiah Meadows  a écrit :
> 
> This could be resolved by checking the underlying non-proxy object and using 
> that one's internal slots instead, in each language-level method that checks 
> that.
> 

Such semantics could make impossible to write impermeable proxies for some 
objects, e.g.

```js
let s = new Set
let sProxy = new Proxy(s, { /*  */ })
Set.prototype.add.call(sProxy, "foo") // will add "foo" to `s`, even if you 
were careful enough to intercept `sProxy.add("foo")`
Set.prototype.has.call(sProxy, "bar") // will reveal whether "bar" is in `s`
```

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Wrapping regex's with proxies isn't working

2016-11-10 Thread Claude Pache

> Le 10 nov. 2016 à 14:59, Angel Scull  a écrit :
> 
> Hello,
> 
> I’ve tried this code and seems that there is some weird type checking 
> somewhere that causes this exception. 
> 
> TypeError: Method RegExp.prototype.exec called on incompatible receiver 
> [object Object]
> 
> 
> let pattern = 
> /^[a-zA-Z0-9\-\._]+@[a-zA-Z0-9\-_]+(\.?[a-zA-Z0-9\-_]*)\.[a-zA-Z]{2,3}$/;
> 
> let patternProxy = new Proxy(pattern,{});
> 
> patternProxy.test('myusern...@mycompany.com')

This is because the `exec` method of `pattern` is internally called with 
`patternProxy` as its receiver (i.e, its "this argument"), and `patternProxy` 
is not a regexp. This is a general issue with proxies, and not a bug.

A simple adhoc workaround is to bind the `exec` method of that particular 
`pattern` to `pattern` itself:

```js
pattern.exec = pattern.exec.bind(pattern)
```

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Power operator, why does -2**3 throws?

2016-10-20 Thread Claude Pache

The existence of traps in the language is not an argument for adding other ones.
On the contrary, we must learn from previous problematic design decisions, in 
order not to repeat the same errors.

Also, the language feeling more quirky is less a severe issue than the language 
inducing to produce more bugs.

—Claude


> Le 20 oct. 2016 à 08:27, medikoo  a écrit :
> 
> ES is already not free from such cases, e.g. `!'property' in object` will
> also not resolve as most will expect.

> 
> I understand and agree that case is ambigous and is problematic. It just
> feels very controversial to me that it was decided that this case will be
> handled differently than others that share exactly same problem.
> 
> For those who are not aware of all such quirks/inconsistences it leaves
> feeling that language is unpredictable in its behaviors.
> 
> On 10/18/2016 01:05 AM, medikoo wrote:
>> There are many other cases when with no parens involved, people have
>> different expectations on the outcome.
>> If expression looks ambigous the actual result always depends on operators
>> precedence, it's how language worked for years, and I don't remember any
>> big
>> problems due to that.
>> 
>> 
>> Jordan Harband wrote
>>> It's quite simple (as has already been stated): some people expect `-x **
>>> y` to be `-(x ** y)`. Some expect it to be `(-x) ** y`.
>>> 
>>> The early SyntaxError ensures that nobody is confused - programmers will
>>> immediately add parens to disambiguate.
>>> 
>>> Avoiding a potential footgun for the next 50 years, at the insignificant
>>> cost of adding two characters so that it parses seems like a very cheap
>>> price to pay.
>>> 
>>> On Tue, Oct 18, 2016 at 12:20 AM, medikoo 
>>> medikoo+mozilla.org@
>>> 
>>> wrote:
>>> 
 I must say throwing here, instead of relying on math dictated operators
 precedence looks really bad.
 It's very surprising to those well experienced with the language, and
 totally inconsistent with how operators worked so far (there is no
 previous
 case where one will throw for similar reason).
 
 Also argument that it's inconsistent with Math.pow(-2, 2), is total miss
 in
 my eyes.
 I believe to most programmers `Math.pow(-2, 2)`, translates to
 `(-2)**(2)`
 and not to `-2**2`,
 same as `Math.pow(a ? b : c, 2)` intuitively translates to `(a ? b :
 c)**(2)` and not to `a ? b : c**2`
 
 
 
 
 --
 View this message in context: http://mozilla.6506.n7.nabble.
 com/Power-operator-why-does-2-3-throws-tp359609p359731.html
 Sent from the Mozilla - ECMAScript 4 discussion mailing list archive at
 Nabble.com.
 ___
 es-discuss mailing list
 
>>> es-discuss@
 https://mail.mozilla.org/listinfo/es-discuss
 
>>> ___
>>> es-discuss mailing list
>>> es-discuss@
>>> https://mail.mozilla.org/listinfo/es-discuss
>> 
>> 
>> 
>> 
>> --
>> View this message in context:
>> http://mozilla.6506.n7.nabble.com/Power-operator-why-does-2-3-throws-tp359609p359733.html
>> Sent from the Mozilla - ECMAScript 4 discussion mailing list archive at
>> Nabble.com.
>> ___
>> es-discuss mailing list
>> es-discuss@
>> https://mail.mozilla.org/listinfo/es-discuss
> 
> 
> ___
> es-discuss mailing list
> es-discuss@
> https://mail.mozilla.org/listinfo/es-discuss
> 
> 
> 
> 
> 
> --
> View this message in context: 
> http://mozilla.6506.n7.nabble.com/Power-operator-why-does-2-3-throws-tp359609p359853.html
> Sent from the Mozilla - ECMAScript 4 discussion mailing list archive at 
> Nabble.com.
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Why Number(symbol) crashes?

2016-10-14 Thread Claude Pache

> Le 11 oct. 2016 à 11:07, medikoo  a écrit :
> 
> I was searching the archived but wasn't able to find the answer.
> 
> What's the reasoning behind having Number(symbol) crash instead of returning
> NaN (as it's in case all other non-coercible values?). It feels not
> consistent.
> 
> If someone can point me to some discussion that provided the reasoning I'd
> be grateful
> 

I believe that the reason of the inconsistency is more an accident of history 
in the development of ES6 than a well-reasoned design decision. Here is my 
understanding:

* At one point of time in the development of ES6, /implicit/ conversion from 
symbol to string or number was made forbidden. This is a behaviour that was 
discussed and decided, in order to prevent silent bugs in computed properties 
in situations where a string was previously implicitely expected.

```js
var key = Symbol()
foo[‘key + ‘-suffix’] // TypeError: can’t convert symbol to string
foo[‘key + ‘42] // TypeError: can’t convert symbol to number
```

* However, /explicit/ conversion from symbol to string (using `String(…)` or 
`.toString()`) has been kept as allowed. This is a more debatable decision 
(with pros and cons). On the other hand, I don’t recall any discussion about 
making explicit conversion from symbol to number different from the implicit 
one, nor anyone complaining that it remained the only primitive type to which 
symbol could not be *explicitly* coerced.

—Claude


___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Power operator, why does -2**3 throws?

2016-10-14 Thread Claude Pache

> Le 14 oct. 2016 à 16:52, Rick Waldron  a écrit :
> 
> Python is also inconsistent: 
> 
> >>> pow(-2, 2)
> 4
> >>> -2 ** 2
> -4
> >>>

This is not inconsistency, but that follows from operator precedence rules 
(those used in mathematics, not in C).

In the same vein, you have `pow(1+1, 2) == 4` but `1+1 ** 2 == 2`, because the 
latter is interpreted as `1+(1 ** 2)`.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Existential Operator / Null Propagation Operator

2016-10-13 Thread Claude Pache
 

> Le 13 oct. 2016 à 19:20, Bob Myers  a écrit :
> 
> Why is this needed? Why are people trying to get the property of an object 
> which is null? Why is the object null in the first place?

This is not about trying to get something from null, but about taking different 
paths according to when a reference is null or not without needing to assign to 
temporary variables, writing complete `if` structures, and/or repeating oneself.

> (...)
> 
> Just as an example, consider the following idiom for null propagation:
> 
> ```
> a ? a.b ? a.b.c : undefined : undefined
> ```
> 
> We can leverage this pattern by allowing the `:` in the ternary operator to 
> be omitted (defaulting to undefined), allowing us to write:
> 
> ```
> a ? a.b ? a.b.c
> ```
> 
> Whether you love it or hate it, at least this solves more problems that just 
> null propagation. I'm not seriously suggesting this. I'm just saying we need 
> to be more creative in brainstorming possible solutions to the problem.

You can already write`a && a.b && a.b.c` in JS... but you still have to repeat 
`a` thrice and`b` twice, which is an issue if `a` and `b` are complex or 
lengthy expressions. Sometimes I am tempted to write something in the lines of 
`(_ = a.b) && _.c` in order to avoid the issue, but it is less readable.

Here is a more complex although somewhat contrived example: If an  
element named "foo" is inside a  section, open the latter in order to 
reveal the former:

```js
document.querySelector("input[name=foo]")?.closest(".details")?.open = true
```

(The short-circuiting mechanism, which is an important part of the semantics in 
my proposal, ensures that the assignment is performed only when the expressions 
just before the `?`s are not null/undefined.)

—Claude
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Existential Operator / Null Propagation Operator

2016-10-13 Thread Claude Pache

> Le 13 oct. 2016 à 17:32, Isiah Meadows  a écrit :
> 
> It may be a good idea to create a pull request for it if it isn't listed yet
> 
I've already tried some time ago: https://github.com/tc39/ecma262/pull/340

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Existential Operator / Null Propagation Operator

2016-10-13 Thread Claude Pache

> Le 13 oct. 2016 à 17:14, Kagami Rosylight  a écrit :
> 
>  
> >IIRC the proposed syntax for computed properties was x?.[y],
>  
> Yes you’re right, sorry :/
>  
> IMO it still seems the syntax problem is the main reason why this proposal 
> has stalled. If not, what is the problem here?

The issue with `?.[` is that it is considered as not pretty by some people. A 
syntax that is at the same time pretty, technically working, and not confusing 
is difficult to find.

Concerning your suggestion of using `!`: From a technical point of view, using 
`![` instead of `?.[` may work only if you forbid a line terminator before the 
`!`, because the following program is valid as of today (with implied 
semicolons):

```js
foo
![42]
```

> I’m curious why this proposal is not even listed in stage 0 proposal list.

Because no representative of TC39 has volunteered to champion it.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Existential Operator / Null Propagation Operator

2016-10-13 Thread Claude Pache

> Le 13 oct. 2016 à 14:37, Kagami Rosylight  a écrit :
> 
>  
> Or `!.`, which unfortunately is now being used by TypeScript?

What is exactly the issue you're trying to solve? The token `?.` works fine 
(technically with a simple lookahead for excluding digit after it). —Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Feature Request: Make ECMA262 a superset of JSON

2016-09-30 Thread Claude Pache
Besides U+2028 and U+2029, there is also the __proto__ key, which has a special 
meaning in JS as implemented in browser. That prevents definitely to "safely" 
embed arbitrary JSON within JS.

—Claude

> Le 29 sept. 2016 à 23:21, Richard Gibson  a écrit :
> 
> ECMAScript claims JSON as a subset twice in 
> https://tc39.github.io/ecma262/#sec-json.parse 
>  , but (as has been 
> well-documented) that is not true because it JSON strings can contain 
> unescaped U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR while 
> ECMAScript strings cannot. Mark Miller alludes to a pre-ES5 push for allowing 
> them (which ultimately failed) in 
> https://esdiscuss.org/topic/json-stringify-script#content-17 
>  , and posits 
> that a repeat today would also fail. Having never seen a windmill that didn't 
> need slaying, I hereby make the attempt.
> 
> Aside from slightly simplifying the spec (by eliminating the need for a 
> production specific to JSON.parse) and retroactively validating its claims, 
> such a change to _DoubleStringCharacter_ and _SingleStringCharacter_ would 
> allow safely embedding arbitrary JSON directly within ECMAScript, a request 
> which has been made before in the context of source 
> concatenation/construction.
> 
> User-visible effects from the change would be limited to the absence of 
> SyntaxError s from code like `eval(' "\u2028" ')` or its raw-text equivalent.
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Array.prototype.first() and Array.prototype.last()

2016-09-28 Thread Claude Pache

> Le 28 sept. 2016 à 07:38, 段垚  a écrit :
> 
> Because `foo.bar` is equivlant to `foo['bar']` in JS so far, and `array.-1` 
> could break this consistency.
> 
> 
> On the other hand, `array.first()` seems not necessary because `array[0]` is 
> even more handy; `array.last()` looks fine to me.
> 
> If someone prefer a more general solution, I recommand `array.get(n)`:
> 
>   * if n >= 0 && n < array.length: equivlant to array[n]
>   * if n < 0 && -n < array.length: equivlant to array[array.length + n]
>   * if n <= -array.length || n >= array.length: throw or return undefined
>   * if n is not a integer or not a number: throw or return undefined
> 
> The last 2 rules make `array.get(n)` less error prone than `array[n]`. I 
> prefer throwing, but maybe returning undefined is more JS-style?

For consistency with the rest of the builtin library, `array.get(n)` should be 
equivalent to `array.slice(n)[0]`, which means: convert `n` to an integer, and: 
return `undefined` for out-of-bound index.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Syntax Proposal: Anonymous Arguments

2016-09-26 Thread Claude Pache

> Le 23 sept. 2016 à 20:35, Kenneth Powers  a écrit :
> 
> As for resolving ambiguity, why not just do what Scala does 
> ?
>  It would seem to me that nesting these functions would be a sign you need to 
> refactor anyway. 

Concretely, when you write:

```js
listOfNumbers.map(Math.floor(@) + 1)
```

what does it mean:

```js
_ => listOfNumbers.map(Math.floor(_) + 1) // (1)
listOfNumbers.map(_ => Math.floor(_) + 1) // (2)
listOfNumbers.map(Math.floor(_ => _) + 1) // (3)
```

? Although the most reasonable interpretation for a human would be (2), because 
the parser is unable to read your mind or to make a qualitative distinction 
between `listOfNumbers.map ` and `Math.floor` (both are just functions), it 
will most probably misinterpret it as (3).

That syntax looks like an attractive nuisance to me.

—Claude

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Optional Chaining (aka Existential Operator, Null Propagation)

2016-08-25 Thread Claude Pache

> Le 25 août 2016 à 17:17, Claude Pache <claude.pa...@gmail.com> a écrit :
> 
> 
>> Le 25 août 2016 à 16:05, Alexander Mekhonoshin <invn...@yandex-team.ru 
>> <mailto:invn...@yandex-team.ru>> a écrit :
>> 
>> 
>> 2. unary ?.
>> 
>> window?.navigator?.toString()
>> 
>> browser: "[object Navigator]"
>> node: ReferenceError: window is not defined
>> 
>> here i suggest syntax for exception-slient accesing globals:
>> 
>> ?.a === hostGlobalObject?.a
>> ?.a?.b === hostGlobalObject?.a?.b
> 
> For accessing the global object, I think that the current System.global 
> proposal is a better call, because it adds no syntax. See:
> 
> https://github.com/tc39/proposal-global 
> <https://github.com/tc39/proposal-global>
> 
> `System.global?.navigator.toString()` is somewhat lengthy, but it is 
> nevertheless simple and clear.
> 

Correction: `System.global.navigator?.toString()`


> —Claude


___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Optional Chaining (aka Existential Operator, Null Propagation)

2016-08-25 Thread Claude Pache

> Le 25 août 2016 à 16:05, Alexander Mekhonoshin  a 
> écrit :
> 
> 
> 
> 3. groupped ?.()
> Syntax for the full existential chain case:
> 
> .?(a.b.c) // equals with typeof a !== 'undefined' && a.b && a.b.c
> 

In other words, `.?(a.b.c)` (or whatever other syntax) is approximately 
equivalent to `a?.b?.c`.

The advantage of such a shortcut should be weighted against the burden of 
learning yet another syntax. On that subject, I recommend to read:

https://esdiscuss.org/topic/the-tragedy-of-the-common-lisp-or-why-large-languages-explode-was-revive-let-blocks

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Optional Chaining (aka Existential Operator, Null Propagation)

2016-08-25 Thread Claude Pache

> Le 25 août 2016 à 16:05, Alexander Mekhonoshin  a 
> écrit :
> 
> 
> 2. unary ?.
> 
> window?.navigator?.toString()
> 
> browser: "[object Navigator]"
> node: ReferenceError: window is not defined
> 
> here i suggest syntax for exception-slient accesing globals:
> 
> ?.a === hostGlobalObject?.a
> ?.a?.b === hostGlobalObject?.a?.b

For accessing the global object, I think that the current System.global 
proposal is a better call, because it adds no syntax. See:

https://github.com/tc39/proposal-global

`System.global?.navigator.toString()` is somewhat lengthy, but it is 
nevertheless simple and clear.

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Symbol.hasInstance and [[Get]] vs [[GetOwnProperty]]

2016-08-23 Thread Claude Pache
>> ```js
>> Uncaught TypeError: Cannot read property 'call' of undefined
>> ```
>> 
> 
> (...)
> 
> Also, reading the message of your TypeError, I wonder if Babel may also fail 
> unexpectedly in case SomeClass does not inherit the standard `Function#call`, 
> as in: ```class SomeClass { static call() { throw "Pwnd!" } }```.

Correction: The potential issue I was thinking of, is when 
`SomeClass[Symbol.hasInstance]` does not inherit the standard `Function#call`:

```js
class SomeClass { 
static [Symbol.hasInstance]() { /* foo */ }
}
SomeClass[Symbol.hasInstance].call = function () { throw "Pwnd!" }
```

which is quite a corner case.

—Claude


___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Symbol.hasInstance and [[Get]] vs [[GetOwnProperty]]

2016-08-23 Thread Claude Pache

> Le 24 août 2016 à 03:35, /#!/JoePea  a écrit :
> 
> > if you want to revert to the default behavior set the value of B or C’s 
> > [Symbol.hasInstance] own property to undefined.
> 
> That just causes errors. In my environment (Babel),
> 
> ```js
> Object.defineProperty(SomeClass, Symbol.hasInstance, {
> value: undefined
> })
> 
>  // ...
> 
> someClass instanceof SomeClass // error
> ```
> 
> results in 
> 
> ```js
> Uncaught TypeError: Cannot read property 'call' of undefined
> ```
> 

If that’s the case, it's a bug (or limitation?) of Babel, as the spec is clear, 
see: https://tc39.github.io/ecma262/#sec-instanceofoperator

Also, reading the message of your TypeError, I wonder if Babel may also fail 
unexpectedly in case SomeClass does not inherit the standard `Function#call`, 
as in: ```class SomeClass { static call() { throw "Pwnd!" } }```.

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Symbol.hasInstance and [[Get]] vs [[GetOwnProperty]]

2016-08-16 Thread Claude Pache
Your mileage may vary, but for me it is, on contrary, intuitive that a subclass 
inherits by default all the methods of its superclass, without arbitrary 
exceptions such as `[Symbol.hasInstance]()`.

Whether it is desirable, I am sure it depends on what you put in the 
`[Symbol.hasInstance]()` method. But the situation for that particular method 
is the same as for any random method: a superclass must be careful if it wants 
to be subclass-friendly.

—Claude

> Le 16 août 2016 à 03:48, /#!/JoePea  a écrit :
> 
> I want to add also that using `super` makes it more readable, but still 
> requires boilerplate code, and is just as statically limited as using a 
> direct reference to a constructor ([I wish it 
> wasn't](https://esdiscuss.org/topic/the-super-keyword-doesnt-work-as-it-should)
>  ):
> 
> ```js
> class A {
> static [Symbol.hasInstance](obj) {
> if (this === A) return false
> else return super[Symbol.hasInstance](obj)
> }
> }
> ```
> 
> /#!/JoePea
> 
> On Mon, Aug 15, 2016 at 6:45 PM, /#!/JoePea  > wrote:
> It seems like using [[Get]] for looking up `@@hasInstance` can be confusing 
> and requires devs to write extra code. For example, suppose we have the 
> following code:
> 
> ```js
> class A {
> static [Symbol.hasInstance] (obj) {
> return false
> }
> }
> 
> class B extends A {}
> class C extends B {}
> 
> let c = new C
> 
> console.log(c instanceof B) // false, but expected true!
> console.log(c instanceof A) // false, as expected
> ```
> 
> The `c instanceof B` check (arguably unintuitively) fails. Defining a 
> `Symbol.hasInstance` method on a base class causes `instanceof` checks on any 
> subclasses to automatically fail unless the developer takes care to write an 
> ugly and fragile workaround:
> 
> ```js
> class A {
> static [Symbol.hasInstance](obj) {
> if (this === A) return false
> else return Function.prototype[Symbol.hasInstance].call(this, obj)
> }
> }
> 
> class B extends A {}
> class C extends B {}
> 
> let c = new C
> 
> console.log(c instanceof B) // true, as expected
> console.log(c instanceof A) // false, as expected
> ```
> 
> That seems likely to introduce errors or headaches.
> 
> What if the lookup for `Symbol.hasInstance` on an object use 
> [[GetOwnProperty]]? Then the first version without the conditional checks 
> would not break subclasses.
> 
> /#!/JoePea
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Why ES6 introduced classes yet `Symbol` not to be used with `new`?

2016-08-15 Thread Claude Pache

> Le 15 août 2016 à 07:33, Kris Siegel  a écrit :
> 
> Interesting.
> 
> Because, to be consistent with Number/String/Boolean you would expect `new 
> Symbol()` to create a  Symbol wrapper object.
> 
> Currently Symbol is the only primitive that can't be converted to a string 
> through the use of the + operator, so why the consistency in one place and 
> the lack thereof in another? I understand there isn't really a meaningful 
> representation of Symbol() as a string but I didn't see any particular reason 
> in my cursory look at the past notes for it to throw an exception so I've 
> been curious.

In short, preventing *implicit* conversion to string is for avoiding silent 
bugs. Typically, in situation where you expect a string, such as:

```js
foo[somePrefix_' + s] = bar[s]
```

This is not an inconsistency at the language level: implicit conversion to 
string is done using `.toString()` or `.@@toPrimitve("string")`, which has 
never been guaranteed to succeed. Example:

```js
var o = Object.create(null)
o + "" // will throw a TypeError
```


> 
> But we anticipated that if `new Symbol` was allowed many devs (who lacked an 
> understanding of the difference between primitive values and wrapper objects 
> for primitive values) would code `new Symbol()` with the expectation that 
> they were creating a Symbol value. This would be a silent bug so we 
> disallowed `new Symbol()`.
> 
> Forgive me for the ignorance but what kind of bug would this introduce?

Examples:

```js
var s = new Symbol
typeof s // "object", not "symbol"

switch (typeof s) {
case "symbol": // will not match
}
```

and:

```js
var s = new Symbol
var o = { }
o[s] = 42 // the wrapper object is converted to a primitive, 
var s2 = Object.getOwnPropertySymbols(o)[0]
s2 == s // true
s2 === s // false
```


> Since Symbol() is already an oddball compared to all other built-in objects 
> and primitives would it have been so bad to simply make `new Symbol()` equate 
> to `Symbol()`? I'm not sure you'll get developers to understand the 
> difference between primitives and wrapper objects (still haven't found one 
> yet who understands this in my inner-circle of JS devs that I know at least).

That would introduce an irregularity in the language, for `new Foo` has always 
been allowed to return an object only, not a primitive. The fact there is some 
lack of understanding among developers is not an excuse for increasing the 
confusion with inconsistent semantics.

The alternative design would have been to specify symbols as true objects 
rather than primitives. I recall that that alternative has been considered and 
discussed during the conception of ES6. You have to dig through the archives in 
order to find why one design was chosen over the other. The only thing I recall 
is that it was not a trivial decision.

—Claude

> 
> 
> On Sun, Aug 14, 2016 at 9:18 PM, Domenic Denicola  > wrote:
> I believe, but am not sure, that we also decided we would follow that pattern 
> for any future primitive types, since in general constructing wrapper objects 
> is a bad idea. (I want to say that wrapper objects themselves are a bad idea, 
> but I think the conclusion was more subtle than that... they are an important 
> part of the semantics, it's just unfortunate that they're so easy to create.)
> 
> If some enterprising person wants to dig through the meeting notes, there 
> might be some hints there...
> 
> > From: Allen Wirfs-Brock [mailto:al...@wirfs-brock.com 
> > ]
> >
> > Because, to be consistent with Number/String/Boolean you would expect `new 
> > Symbol()` to create a  Symbol wrapper object.  But we anticipated that if 
> > `new Symbol` was allowed many devs (who lacked an understanding of the 
> > difference between primitive values and wrapper objects for primitive 
> > values) would code `new Symbol()` with the  expectation that they were 
> > creating a Symbol value. This would be a silent bug so we disallowed `new 
> > Symbol()`.
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org 
> https://mail.mozilla.org/listinfo/es-discuss 
> 
> 
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Object.freezing proxies should freeze or throw?

2016-08-12 Thread Claude Pache
See https://github.com/tc39/ecma262/pull/666 


(I *swear* that the issue number is just a hazard.)

—Claude___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: The Invariants of the Essential Methods are false in case of reentrancy

2016-08-11 Thread Claude Pache

> Le 11 août 2016 à 13:14, Tom Van Cutsem <tomvc...@gmail.com> a écrit :
> 
> I don't think it's too worrisome because of the following reasoning:
> 
> Any code prior to the first invocation of obj.x (let's call this the "outer 
> code") will have observed the property as configurable & writable, so having 
> obj.x evaluate to 1 is a valid outcome.
> 
> Any code that runs synchronously between the call to Object.defineProperty 
> and the `return 1` statement (let's call this the "inner code"), will 
> consistently observe obj.x as non-configurable,non-writable and will always 
> read 2.
> 
> A worrisome scenario would be when the inner code computes results based on 
> the new value of x that are also accessible to the outer code, and the outer 
> code somehow expects that value to be consistent with the old value of x. 
> However, it's unclear that this bug is really due to the violation of an ES 
> invariant.
> 
> I'm not sure if proxies would amplify the problem. Actually, the invariant 
> assertions in the Proxy internal methods were designed precisely to avoid 
> such bugs, which is why all the assertions trigger when the trap has finished 
> executing and the proxy can no longer influence the outcome of the 
> intercepted operation. The bug described above would be avoided if the 
> internal methods of Ordinary ES objects would apply the same kind of 
> invariant checks as proxies do, checking the result of the [[Get]] operation 
> with the property's current attribute state. However, I suspect that would 
> probably be a bridge too far in terms of cost vs payoff.

If we want to avoid the "bug" I mentioned, the invariant checks for proxies 
have to be done very carefully in order to avoid some really weird (and most 
surely implausible) edge cases as demonstrated by the scenario below.
The key fact is that, while the traps of the proxy may behave regularly, the 
target might be itself an exotic object that manifests weird behaviours.

Let P be a Proxy, T its target object, and let's invoke 
P.[[GetOwnProperty]]("x").
https://tc39.github.io/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p
 
<https://tc39.github.io/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p>
The following scenario is possible:

* step 8: P's getOwnPropertyDescriptor trap is invoked on property "x". That 
trap exists but simply returns T.[[GetOwnProperty]]("x")
* step 10: T.[[GetOwnProperty]]("x") returns naturally the same descriptor.
* step 12 (or 11c): T.[[IsExtensible]]() is invoked. But it happens that T is a 
strange exotic object (e.g. a proxy) with a weird [[IsExtensible]] method that 
does the following:
* if it is extensible,
1. it deletes its property "x";
2. it makes itself nonextensible;
3. it publishes somewhere that P is nonextensible and has no 
property "x" (e.g., by using the observe function of my original message);
* Following steps: Checks are made based on results of steps 10 and 12. 
Naturally, given the result of step 10, all checks pass.

As a consequence, the property "x" is observed as present on P, while it was 
previously observed as absent on nonextensible P.

(A solution would be to invoke T.[[IsExtensible]]() only when we know in 
advance that we will throw in case T is nonextensible. But it is probably not 
worth to worry for that.)

—Claude

> 
> Regards,
> Tom
> 
> 
> 2016-08-10 17:51 GMT+02:00 Claude Pache <claude.pa...@gmail.com 
> <mailto:claude.pa...@gmail.com>>:
> Test case:
> 
> ```js
> var results = []
> 
> var observe = function (method, object, ...args) {
> results.push({
> method: method
>   , object: object
>   , args: args
>   , output: Reflect[method](object, ...args)
> })
> }
> 
> var obj = { get x() {
> Object.defineProperty(this, 'x', { value: 2, configurable: false, 
> writable: false })
> observe('getOwnPropertyDescriptor', this, 'x')
> return 1
> } }
> 
> observe('get', obj, 'x')
> 
> results[0]
> // { method: "getOwnPropertyDescriptor", object: obj, args: [ "x" ], output: 
> { value: 2, writable: false, enumerable: true, configurable: false } }
> // `obj` is observed to have a nonconfigurable, nonwritable property "x" with 
> value `2`.
> 
> results[1] // { method: "get", object: obj, args: [ "x" ], output: 1 }
> // Then, `obj.[[Get]]("x") is observed to return `1`.
> ```
> 
> Not sure if it is worrisome. What is sure, the situation could become worse 
> with fanciful proxies.
> 
> ―Claude
> ___
> es-discuss mailing list
> es-discuss@mozilla.org <mailto:es-discuss@mozilla.org>
> https://mail.mozilla.org/listinfo/es-discuss 
> <https://mail.mozilla.org/listinfo/es-discuss>
> 

___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


  1   2   3   4   5   >