Re: effect of editor/ide on javascript programming-style

2019-06-28 Thread Andy Earnshaw
I would agree for Vim in its basic form but have successfully used vim, for
several years, with the Ctrl+P extension to quickly and efficiently get
around codebases with many files. It also has a buffer lookup for accessing
already open files, and other shortcuts like Ctrl+B/Ctrl+6 make switching
between 2 files for simultaneous editing a breeze, which I found invaluable
for writing tests alongside the main code.

Vim gets more productive the more you customise it, but that makes it
harder to use when you're on a different machine without those
customisations. Still, most of the time you'll take your config with you. I
would say that if you feel inefficient at doing something in Vim then it's
something you can work on.

On Fri, 28 Jun 2019, 19:30 kai zhu,  wrote:

> 3 frontend-devs is reasonable and maybe ideal -- but reality is most shops
> can only afford 1 frontend-dev.  i remain convinced 5 js-devs is around the
> practical limit for most products.  going over that magic-number, and
> people become confused about their areas-of-responsibility -- allowing
> mediocrity/siloing to flourish from lack of accountability.
>
> "scalable" javascript tooling/frameworks that allow large-scale
> collaboration are solutions-in-search-of-a-problem.  they should remain as
> in-house solutions for the unique problems faced by
> google/facebook/salesforce/etc, and are inappropriate/overengineered for
> general-purpose product-development.
>
> On Fri, Jun 28, 2019 at 12:58 PM Jordan Harband  wrote:
>
>> As much as I like vim, this seems like more of an argument against using
>> vim than anything for the language - also it's not "usually" just 1
>> frontend developer; altho that may be your experience. I often like to say
>> it's *never* just one - even if it's you, it's also "you in 6 months", and
>> that person is really annoyed with you.
>>
>> As an anecdotal data point, my garage startup which had no funding had 3
>> JS devs working on our frontend. I would argue it's not very cost effective
>> to *under*invest in frontend dev, but obviously everyone has different
>> opinions on that - and it's not relevant to this discussion list.
>>
>> On Fri, Jun 28, 2019 at 9:59 AM kai zhu  wrote:
>>
>>> adding a datapoint on effects of vim-editor on my javascript
>>> coding-style.  this is to expand on discussion of "JavaScript and Syntax
>>> Research Methods" in tc39-notes [1].
>>>
>>> vim has the following file-editing properties:
>>> 1. poor UX in opening new files
>>> 2. efficient content-search/jump/traversal of large files
>>> 3. can display the same file in multiple editing-windows
>>>
>>> because of above properties, i default to writing javascript
>>> applications as a single, large file (which may get broken up if it becomes
>>> "too" large, e.g. >10k sloc).  developing javascript-apps with a single
>>> js-file leads me to:
>>> 1. prefer reusing external-code by copy/pasting it into single-file
>>> rather than load it as commonjs/es-module
>>> 2. be selective about what external-code i want to copy/paste --
>>> generally only self-contained or "rolled-up" ones w/ minimal
>>> external-dependencies
>>> 3. general preference to write self-contained code that easy-to-reuse by
>>> copy/pasting into a new project [2].
>>>
>>> an argument against writing javascript-applications as a single,
>>> self-contained file, is that it leads to merge/commit conflicts when
>>> multiple devs are working on same file.  its valid ... except most
>>> javascript-products are developed by just 1-3 js-devs.  for the frontend,
>>> its usually just 1 developer.  the hype of making javascript "scalable" so
>>> you can have 20x people working on a product is just that -- hype.  there
>>> are very few real-world products where its cost-effective to have more than
>>> 5 js-devs working on it.
>>>
>>> [1] JavaScript and Syntax Research Methods
>>>
>>> https://github.com/rwaldron/tc39-notes/blob/7a4af23d/meetings/2019-06/june-6.md#javascript-and-syntax-research-methods
>>>
>>> [2] documentation of various [minimal-dependency] self-contained
>>> functions that can be copy/pasted
>>>
>>> https://kaizhu256.github.io/node-utility2/build..beta..travis-ci.org/apidoc.html
>>>
>>>
>>>
>>>
>>> screenshot of me vim-editing multiple locations of one, large
>>> javascript-file (each sub-window is a different location of the same file).
>>> [image: vim-editor-min.png]
>>>
>>> ___
>>> 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: Proposal: Exposing native scroll as API

2019-06-24 Thread Andy Earnshaw
As Claude pointed out, Scrolling is not part of ECMAScript. On the subject
of improved support for virtual scrolling, I've started discussions on
CSS-WG and Web Components issue trackers.

https://github.com/w3c/csswg-drafts/issues/3397
https://github.com/w3c/webcomponents/issues/791

Please feel free to add your +1 there or contribute your own use cases to
the discussion.

On Sat, 22 Jun 2019 at 19:41, kai zhu  wrote:

> the referenced video was entertaining to watch (and i learned new things
> about typescript and proxies), but i still don't understand your UX-problem
> -- at least enough to know what/how a new standard-api would help.
>
> there's a bunch of canvas-scrolling examples @
> https://konvajs.org/docs/sandbox/Canvas_Scrolling.html.  examples #1 and
> #4 implement native canvas-scrolling, with the latter having less jankiness
> on my mobile-chrome.  maybe you're asking for consistent #4 css-behavior
> across all mobile-browsers (i have no idea if it works as well in
> ios-safari)?  that would be w3c csswg's domain.
>
> also somewhat-related -- chrome is debating an intent-to-implement feature
> for scrollTo-behavior for text-fragments.
> for example:
> `https://www.example.com#targetText=You%20may%20use%20this%20domain`
> 
> will scroll to element in www.example.com containing text "You may use
> this domain". [1]
>
> [1] Scroll-To-Text using a URL fragment
> https://github.com/bokand/ScrollToTextFragment
>
>
> On Fri, Jun 21, 2019 at 10:33 AM Adam Eisenreich  wrote:
>
>> If you want to have native scrolling experience for `` you need
>> to either implement your own scrolling behaviour, or you will create
>> `` of size much bigger than screen, that way it overflows screen
>> and shows scollbars, but then you must only render on part of canvas as
>> most is hidden.
>>
>> I would like an API I would ask:
>> If this element **would be scrollable**, when scrolling would actually
>> occur? How long would the animation take on this platform? Where the end
>> offset would be?
>> Scrolling isn't same for each platform ex.: PC, Mac, iOS, Android.
>>
>> There is video about proxx, it mentions other problems too, but they
>> explain there how they did implement natural scrolling for ``:
>> https://youtu.be/ViyTYEv9dM8?t=1005
>> ___
>> 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: Proposal: rest operator in middle of array

2019-06-11 Thread Andy Earnshaw
On Mon, 10 Jun 2019 at 22:20, Ethan Resnick  wrote:

> @Andy Perhaps you can provide some links? I found two
> 
> threads  — both 8
> years old — that talked about this, along with one more recent one
> 
> that didn't get very far. In the first two threads, commenters brought up
> one case where the semantics are unclear (i.e., when there are more listed
> binding elements than there are elements in the iterable), and there was
> some talk about implementation complexity. But there was also some interest
> from some big contributors to the spec. So I wonder if it's time to revisit
> this?
>

Here's the one that I was involved in:

https://esdiscuss.org/topic/rest-parameters

My comment was not meant to be dismissive, I was just hoping to provide
some context (and I was on my mobile at the time). If several discussions
have tailed off over the years without anyone making a concrete proposal,
then it seems unlikely that this discussion will make any more progress
than the ones before it. I think the real limiting factor is that this is
not a burning issue for anyone, not a particular pain point in day to day
programming, so there's no big appetite to try and overcome the main
objections.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: rest operator in middle of array

2019-06-06 Thread Andy Earnshaw
This has come up several times and, while it seems pretty intuitive to me,
not everyone seems to agree. You can check the archives for previous
discussions.

On Thu, 6 Jun 2019, 17:54 Ethan Resnick,  wrote:

> Long-time mostly-lurker on here. I deeply appreciate all the hard work
> that folks here put into JS.
>
> I've run into a couple cases now where it'd be convenient to use a rest
> operator at the beginning or middle of an array destructuring, as in:
>
> ```
> const [...xs, y] = someArray;
> ```
>
> Or, similarly, in function signatures:
>
> ```
> function(...xs, y) { }
> ```
>
> The semantics would be simple: exhaust the iterable to create the array of
> `xs`, like a standard rest operator would do, but then slice off the last
> item and put it in `y`.
>
> For example, I was working with some variable argument functions that, in
> FP style, always take their data last. So I had a function like this:
>
> ```
> function match(...matchersAndData) {
>   const matchers = matchersAndData.slice(0, -1);
>   const data = matchersAndData[matchersAndData.length - 1];
>   // do matching against data
> }
> ```
>
> Under this proposal, the above could be rewritten:
>
> ```
> function reduce(...matchers, data) { /* ... */ }
> ```
>
> Another example: a function `pad`, which takes a target length and a
> string to pad, with an optional padding character argument in between:
>
> ```
> function pad(targetLength, ...paddingCharAndOrData) {
>   const [paddingChar = " "] = paddingCharAndOrData.slice(0, -1);
>   const data = paddingCharAndOrData[paddingCharAndOrData.length - 1];
>
>   // pad data with paddingChar to targetLength;
> }
> ```
>
> With this proposal, that could be rewritten:
>
> ```
> function pad(targetLength, ...opts, data) {
>   const [paddingChar = " "] = opts;
>   // pad data with paddingChar to targetLength;
> }
> ```
>
> I'm curious if this has been considered before, and what people think of
> the idea.
>
> Obviously, if `...a` appeared at the beginning or middle of a list, there
> would have to be a fixed number of items following it, so a subsequent rest
> operator in the same list would not be allowed.
>
> Thanks
>
> ___
> 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: Re: Actual WeakSet Use Cases

2019-04-23 Thread Andy Earnshaw
This is pretty much what I used it for in a previous job role. We loaded
and unloaded various iframes, registering APIs and custom elements inside
them, adding the `window` object to a WeakSet so the initialisation only
ran once.

On Tue, 23 Apr 2019 at 10:26, Andrea Giammarchi 
wrote:

> WeakSet can be very useful in general to avoid *any* object to be
> visited/setup twice, not just those coming from user-land classes.
>
> Circular references, mixins, DOM nodes one-off events handling, and so on
> and so fort.
>
> On Mon, Apr 22, 2019 at 8:26 PM #!/JoePea  wrote:
>
>> (I edited the broken format of my previous post)
>>
>> What other use cases are there?
>>
>> On Mon, Apr 22, 2019 at 11:20 AM #!/JoePea  wrote:
>>
>>> > WeakSets are perfect for branding and are how I would expect web
>>> platform class branding to be explained.
>>> >
>>> > ```js
>>> > const foos = new WeakSet();
>>> >
>>> > class Foo {
>>> >   constructor() {
>>> > foos.add(this);
>>> >   }
>>> >
>>> >   method() {
>>> > if (!foos.has(this)) {
>>> >   throw new TypeError("Foo.prototype.method called on an
>>> incompatible object!");
>>> > }
>>> >   }
>>> > }
>>> > ```
>>>
>>> Just curious, is that effectively the same as what the (current)
>>> [private fields proposal](https://github.com/tc39/proposal-class-fields)
>>> offers?
>>>
>>> ```js
>>> class Foo {
>>>   #isFoo = true
>>>
>>>   method() {
>>> if (this.#isFoo) {
>>>   throw new TypeError("Foo.prototype.method called on an
>>> incompatible object!");
>>> }
>>>   }
>>> }
>>> ```
>>>
>>> - Joe
>>>
>> ___
>> 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: Small Proposal "!in"

2018-07-19 Thread Andy Earnshaw
On Thu, 19 Jul 2018 at 14:48 Mike Samuel  wrote:

> On Thu, Jul 19, 2018 at 9:26 AM Michael Theriot <
> michael.lee.ther...@gmail.com> wrote:
>
>> > 'string' === typeof document.createElement('input').type
>> > // true
>>
>> It should be noted this is a "loose check"; it does not determine whether
>> or not the property exists when its value equals undefined. It also
>> triggers getters, whereas `in` reports whether or not the property exists
>> without triggering a getter.
>>
>
> Good point.   `in` does trigger "has" proxy handlers though, so neither is
> side-effect free.
>

Except I'd argue this is a desirable side effect in the case of `in` and
less so in the case of a getter.  Getters are more likely to be an
intensive operation (for example, innerHTML) than a proxy `has` operation
generally overriding the expected behaviour of the target object.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Small Proposal "!in"

2018-07-19 Thread Andy Earnshaw
On Thu, 19 Jul 2018 at 14:44 T.J. Crowder 
wrote:

> On Thu, Jul 19, 2018 at 12:32 PM, Andy Earnshaw
>  wrote:
> > Although I support the idea of `!in` (for the same reasons as T.J.
> Crowder
> > mentioned, plus it's useful for duck typing), what some browsers do
> isn't a
> > great argument as modern browsers follow the spec more closely with
> regards
> > to inherited accessors like this and you'd never be able to use `!in`
> for an
> > older browser.
>
> Well, there's transpiling.
>

Good point.


> > `!in` and `!instanceof` would be great additions to the operator sets.
>
> AND, agreeing with Mike Samuel, an ergonomic operator for `hasOwnProperty`
> (that doesn't have the issues of being overridden, not being inherited
> because `Object.prototype` isn't in the object's prototype chain, etc.)
> would be a great addition. I don't see any reason they couldn't all be
> part of the same proposal as they touch the same parts of the spec and
> implementations. And agree that the own property ones would be the more
> useful ones, but there are use cases for both.
>
> The immediate temptation is `hasOwn` and `!hasOwn`. My only concern is
> that their operands would be in the opposite order to `in` and `!in`:
>

I'm not against this at all.  I just think the arguments against `!in`
aren't really arguments against it.  Adding `!hasOwn` would give even more
weight to an `!in` proposal, I think.


> For me, `hasOwn` with the different operand order isn't a problem, but
> others may take a different view. Trying to keep the same order takes us
> down a route like `inOwn` which I can't say I care for.
>

Nor me. I would argue for `on` (`'a' on b`), but that is a huge typo
footgun (especially for Colemak users) and maybe isn't clear enough about
its semantics.  I would argue that operators aren't camel cased in JS
though, so `hasown`/`inown`.


>
> But I wonder if all of this discussion is useful. If someone *did* take
> the time to work out the naming and do a proper draft proposal, perhaps a
> Babel plugin, is there really any likelihood of someone championing it? I'd
> see these contents:
>
> * `name !in obj`, `name notin obj`, or whatever it gets called
> * `obj hasOwn name`, `name inOwn obj`, or whatever it gets called
> * `obj !hasOwn name`, `name !inOwn obj`, or whatever it gets called
> * `Reflect.hasOwn`, the "own" version of `Reflect.has`
> * `Proxy` trap for `hasOwn` (even if the operator has a different name)
>
> Is there anyone appropriately-placed who can say "Yeah, if someone spends
> the time to investigate this and put together a really proper proposal, I'm
> willing to look at that proposal with an eye toward _possibly_ championing
> it." I mean, if there's a 10% chance or better, it may be worth someone's
> time. If there isn't, then...
>

`!in` and `!instanceof` are low hanging fruit (run the same steps as their
counterparts but flip the result), better off in their own proposal. I
don't know if you'd find a champion to do it, but I do think a lot of
people would find them convenient.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Small Proposal "!in"

2018-07-19 Thread Andy Earnshaw
It was a contrived example I threw together to make a point in 30 seconds.
It may surprise you to know that it is not real world code.  You talk about
an "attacker" as if any code working in such a way is sensitive, but that
is often not the case and leaving your functions intentionally generic
allows third parties more room when working with it.

> 'string' === typeof document.createElement('input').type
> // true

Again, you're missing the point, which is how that is one example of an
object that doesn't 'own' all of its properties.  As already mentioned, it
also triggers a getter.

Let's not also forget that not all code has to adhere to best practices.  I
use the `in` operator far more in the REPL/console or when I'm prototyping
than I do when I'm performing robust checks in code.

On Thu, 19 Jul 2018 at 13:23 Mike Samuel  wrote:

> On Thu, Jul 19, 2018 at 7:32 AM Andy Earnshaw 
> wrote:
>
>> Although I support the idea of `!in` (for the same reasons as T.J.
>> Crowder mentioned, plus it's useful for duck typing), what some browsers do
>> isn't a great argument as modern browsers follow the spec more closely with
>> regards to inherited accessors like this and you'd never be able to use
>> `!in` for an older browser.  However, you do have a point in that accessors
>> can live anywhere in the prototype chain and an object's properties may not
>> necessarily be 'owned' by the object in question:
>>
>> document.createElement('input').hasOwnProperty('type')
>> // false
>>
>
> 'string' === typeof document.createElement('input').type
> // true
>
>
>> So far, the main argument against has been that `hasOwnProperty()` is
>> recommended over `in` as a more robust check.  I don't see how this is a
>> valid concern, they clearly have different use cases and you're not going
>> to solve that problem be excluding a negated `in` from the spec (`!(a in
>> b)` is still easier to type than `!b.hasOwnProperty(a)`).  There are plenty
>> of valid use cases for `in`, not least duck typing as mentioned before:
>>
>
> Agree re "not solving that problem by"
> When I'm duck typing, I typically am testing typeof or truthiness of a
> property, not just presence.
>
> function feed(duck) {
>> if ('quackPitch' in duck && duck.canSwim) {
>> duck.give(defrostedPeas);
>> }
>> }
>>
>
> This code is brittle.  An attacker may be able to deny service by getting
> `{ "quackPitch": true, "canSwim": true }` to a JSON decoder, but would not
> be able to trigger an exception if you tested with typeof instead of in.
>
> function robustFeed(duck) {
>   if (duck.canSwim && typeof duck.give === 'function') {
> duck.give(defrostedPeas);
>   }
> }
>
> `in` provides a weak, confusable kind of duck typing.
> JSON decoding attacks allow forging objects that satisfy `in` predicates,
> encouraging conflating
> objects from an untrusted source with objects from trusted code.
> These forgeries often would not pass stronger predicates that test for the
> typeof required properties.
>
>
>> `!in` and `!instanceof` would be great additions to the operator sets.
>>
>
> Agree re !instanceof.  I'm still not seeing where developers do and should
> use `in` or `!in` on a regular basis.
>
>
>> On Thu, 19 Jul 2018 at 12:06 Tobias Buschor 
>> wrote:
>>
>>> There are valid use-cases.
>>> As an example, some browsers have "onfocus" as an own property of
>>> "window", some as an inherited.
>>>
>>> ```js
>>> if ('onfocus' !in window) {
>>> // polyfill onfocus...
>>> }
>>> ```
>>>
>>>
>>> Am Mi., 18. Juli 2018 um 18:32 Uhr schrieb Mike Samuel <
>>> mikesam...@gmail.com>:
>>>
>>>>
>>>>
>>>> On Wed, Jul 18, 2018 at 12:21 PM Michael Theriot <
>>>> michael.lee.ther...@gmail.com> wrote:
>>>>
>>>>> I think it is irrelevant; the operator already exists and I would
>>>>> assume if you want the negation of it you are using it correctly in the
>>>>> first place. Otherwise are you not just arguing for its removal 
>>>>> altogether?
>>>>> But to answer your question one case that comes to mind is trapping 
>>>>> get/has
>>>>> in a proxy handler.
>>>>
>>>>
>>>> Why should we assume that only people who consistently use `in`
>>>> correctly would want the negation?  It seems that people who use it
>>>> incorrectly becaus

Re: Small Proposal "!in"

2018-07-19 Thread Andy Earnshaw
Although I support the idea of `!in` (for the same reasons as T.J. Crowder
mentioned, plus it's useful for duck typing), what some browsers do isn't a
great argument as modern browsers follow the spec more closely with regards
to inherited accessors like this and you'd never be able to use `!in` for
an older browser.  However, you do have a point in that accessors can live
anywhere in the prototype chain and an object's properties may not
necessarily be 'owned' by the object in question:

document.createElement('input').hasOwnProperty('type')
// false

So far, the main argument against has been that `hasOwnProperty()` is
recommended over `in` as a more robust check.  I don't see how this is a
valid concern, they clearly have different use cases and you're not going
to solve that problem be excluding a negated `in` from the spec (`!(a in
b)` is still easier to type than `!b.hasOwnProperty(a)`).  There are plenty
of valid use cases for `in`, not least duck typing as mentioned before:

function feed(duck) {
if ('quackPitch' in duck && duck.canSwim) {
duck.give(defrostedPeas);
}
}

`!in` and `!instanceof` would be great additions to the operator sets.

On Thu, 19 Jul 2018 at 12:06 Tobias Buschor 
wrote:

> There are valid use-cases.
> As an example, some browsers have "onfocus" as an own property of
> "window", some as an inherited.
>
> ```js
> if ('onfocus' !in window) {
> // polyfill onfocus...
> }
> ```
>
>
> Am Mi., 18. Juli 2018 um 18:32 Uhr schrieb Mike Samuel <
> mikesam...@gmail.com>:
>
>>
>>
>> On Wed, Jul 18, 2018 at 12:21 PM Michael Theriot <
>> michael.lee.ther...@gmail.com> wrote:
>>
>>> I think it is irrelevant; the operator already exists and I would assume
>>> if you want the negation of it you are using it correctly in the first
>>> place. Otherwise are you not just arguing for its removal altogether? But
>>> to answer your question one case that comes to mind is trapping get/has in
>>> a proxy handler.
>>
>>
>> Why should we assume that only people who consistently use `in` correctly
>> would want the negation?  It seems that people who use it incorrectly
>> because they are confused about the precise semantics or don't care might
>> want the negation too.  If there are more of the latter then we should not
>> assume what you assume.
>>
>> Proxy handler code is important, but very few developers will ever write
>> a proxy handler over their careers, so this seems like a marginal use case.
>> Besides, Reflect.has is probably a better choice in a proxy handler.
>>
>> I am not arguing for removing `in`.  That would break the web.  I am just
>> arguing for prioritizing changes that provide features that more closely
>> match the semantics developers typically want over making it more
>> convenient to write code that seems to work in casual testing but has
>> subtly wrong semantics.
>>
>>
>>
>>
>>
>>
>>
>>> On Wednesday, July 18, 2018, Mike Samuel  wrote:
>>>


 On Wed, Jul 18, 2018 at 11:05 AM Michael Theriot <
 michael.lee.ther...@gmail.com> wrote:

> I think `in` and `instanceof` could both benefit from having negated
> versions.
>
> Assuming the developer is using `in` correctly, hasOwnProperty
> concerns are irrelevant. Either way they would attempt to use !(a in b),
> not !hasOwnProperty.
>

 Why should we assume the developer is using `in` correctly?
 Apologies if I buried my question at the end.  It was, what are the use
 cases for `in` that would not be better served by an ergonomic, infix
 hasOwnProperty?


 Same reason we don't use...
> !(a == b) // a != b
> !(a === b) // a !== b
>


> !(a > b) // a <= b
> (!(a > b) && !(a == b)) // a < b
>

 I'm not sure this is relevant to your larger point, and I've already
 conceded ergonomics, but
 these last two are not equivalent because NaN is weird.

 a = NaN, b = 0
 [!(a > b), a <= b]  // [true, false]
 [!(a > b) && !(a == b), a < b]  // [true, false]





> On Thursday, June 28, 2018, Tobias Buschor 
> wrote:
>
>> I dont like to write:
>> if ( !('x' in obj) &&  !('y' in obj) ) {
>>  doit()
>> }
>>
>> I was even tempted to write it that way:
>> if ('x' in obj  ||  'y' in obj) { } else {
>>  doit()
>> }
>>
>> What about a !in operator to write it like this?
>> if ('x' !in obj  &&  'y' !in obj) {
>>  doit()
>> }
>>
>> ___
> 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
>>
>
>
> --
> Freundliche Grüsse
> Tobias Buschor
>
> schwups GmbH
> Hauptstr. 33
> 9424 Rheineck/SG
>
> +41 76 321 23 21 

Re: Suggestion: Destructuring object initializer.

2018-02-09 Thread Andy Earnshaw
Bob, I think it's an interesting idea too, but you can't strong-arm people
into getting excited about what you're asking for.  If it really is that
important to you then put together a solid proposal, write a Babel plugin
and then try to find a champion for it.

On Thu, 8 Feb 2018 at 14:05 Bob Myers  wrote:

> It does make one stop and wonder why the group will endlessly entertain
> trolls debating whether or not ES6 (or ES5) portends the end of
> civilization as we know it, while relentlessly ignoring literally dozens of
> similar/identical proposals for property picking, a feature which easily
> contributes as much to the language at as little cost as many other
> features such as spread properties.
>
> Bob
>
> On Thu, Feb 8, 2018 at 4:15 PM, Bob Myers  wrote:
>
>> This extremely useful feature, which is sometimes called "picking", has
>> been discussed extensively on the group, but the "thought leaders" (?) who
>> apparently have the ability to kill a feature by saying "I don't really
>> think it's that important" have failed to get excited about it, although it
>> seems to me to be at least as "interesting" (in terms of the unwritten
>> criteria apparently applied to determine "interesting") as many other
>> features which are progressing through the ES39 life-cycle, and the nature
>> of the TC39 governance process, which gives entirely new meaning to the
>> notion of "design by committee", makes it impossible to find the champion
>> which is the gating factor for the entire process.
>>
>> Bob
>>
>> On Thu, Feb 8, 2018 at 3:15 PM, Yeong-u Kim  wrote:
>>
>>> # Suggestion: Destructuring object initializer.
>>>
>>> --
>>>
>>>  Destructuring assignment: it extracts values by destructuring an
>>> object, and assign _them_ to ‘variables.’ I suggest Destructuring object
>>> initialization syntax; it is similar to Destructuring assignment, except
>>> that it initializes an object with _the extracted values_.
>>>
>>> ```javascript
>>> const name_info = {"first name": "Yeong-u", "last name": "Kim",
>>> nickname: "K."};
>>> const e = "computed property name";
>>>
>>> const object = {
>>> name: {
>>> *{"first name": forename, "last name": surname}: name_info
>>> },
>>> *[a, b, c]: [1, 2, 3],
>>> *[d]: [4],
>>> [e]: "This is not part of the syntax"
>>> *[{"some property name": "new one"}]: [{"some property name": 5}],
>>> *{gettable: something}: {get gettable() {return Symbol("Using
>>> [[Get]]");}}
>>> };
>>> /*
>>> {
>>> name: {
>>> forename: "Yeong-u",
>>> surname: "Kim"
>>> },
>>> a: 1,
>>> b: 2,
>>> c: 3,
>>> d: 4,
>>> "computed property name": "This is not part of the syntax",
>>> "new one": 5,
>>> something: Symbol(Using [[Get]])
>>> }
>>> */
>>> ```
>>>
>>> --
>>>
>>>  I would appreciate hearing your opinion on this.
>>>
>>>
>>> ___
>>> 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: the syntax let decorators ?

2018-01-11 Thread Andy Earnshaw
I don't like this syntax.  `let` can be used to declare multiple variables,
so how does this work?

```
@inc
let a = 1,
b = 2;
```

Does it only decorate the first, or does it decorate all?  Either way, I
don't think it's flexible enough to be compatible with certain coding
styles.  If it is ever going to work, the decorator should come before the
variable name:

```
let @inc a = 1,
@inc b = 2;
```

On Wed, 27 Dec 2017 at 10:48 郑宇光  wrote:

> do you like syntax like this
>
> ```
> @inc
> let a = 1;
>
> function inc(value) {
>   return value + 1;
> }
> ```
>
> I write a plugin to enable this syntax for test, [javascript let
> decorators](https://github.com/ukari/javascript-let-decorators)
> ___
> 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: Re: An update on rest operator ?

2017-08-03 Thread Andy Earnshaw
I think T.J. had the most intuitive logic (and this has been mentioned in
previous threads too), where non-rest parameters have priority:

```
const [a, ...rest, c] = [1] // -> 1, [], undefined
const [a, ...rest, c] = [1, 2] // -> 1, [], 2
const [a, ...rest, c] = [1, 2, 3] // -> 1, [2], 3
```

If you think of rest as "everything else" (which is what it already is)
then this feels pretty natural and is easy to reason about.


On Thu, 3 Aug 2017 at 10:18 James Browning 
wrote:

> The 1, 1 would happen if you decided that `[a, ...rest, b]` read in both
> directions (although personally I'm not a fan of this approach) e.g.
>
> ```
> const arr = [1]
> const [a, ...rest, b] = arr
>
> // Roughly equivalent to:
> const [a] = arr.slice(0, 1)
> const [c] = arr.slice(-1) // So they get duplicated
> const rest = arr.slice(1, -1) // Empty
>
> //  Similarly for a longer array
>
> const arr = [1, 2]
> const [a, b, ...rest, c, d] = arr
>
> // Would be roughly equivalent to
>
> const [a,b] = arr.slice(0, 2)
> const [d, c] = arr.slice(-2).reverse()
> const rest = arr.slice(2, -2) // Which is empty in this case
> ```
>
> ---
>
> One option could be (although I don't like it either) to allow the rest
> operator to have a direction e.g.:
>
> ```
> const [a, ...rest, b] = [1] // a -> 1, b -> undefined
> // And the other way
> const [a, rest..., b] = [1] // a -> undefined, b -> 1
> ```
>
> Personally I think that'd make it more confusing, but it's potentially an
> option.
>
> Another option could even be that `[a, ...rest, b]` simply throws on an
> iterable with less than 2 items, but that's not consistent with the current
> behavior of `[a, b]` not throwing on iterables with less than 2 items.
> ___
> 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: Are thrown errors in a try block considered to be handled even if there's no catch block?

2017-06-23 Thread Andy Earnshaw
Thanks, Domenic, I had a quick look at that and I hope that other
implementers show some interest.  It's certainly a step in the right
direction, although it also suffers from not being able to break on
(caught) exceptions in the debugger.

I know that there are also efforts to allow EventTarget construction; I saw
your PR for this the other day.  That's probably what I would use in the
future.

On Fri, 23 Jun 2017 at 14:16 Domenic Denicola <d...@domenic.me> wrote:

> Indeed, you cannot replicate dispatchEvent’s behavior, because it catches
> the error, then uses a browser-specific primitive “report an exception”.
> Over in the HTML spec, we’ve suggested exposing that primitive to users,
> but it hasn’t garnered sufficient implementer interest; see
> https://github.com/whatwg/html/pull/1196.
>
>
>
> *From:* es-discuss [mailto:es-discuss-boun...@mozilla.org] *On Behalf Of *T.J.
> Crowder
> *Sent:* Friday, June 23, 2017 07:01
> *To:* Andy Earnshaw <andyearns...@gmail.com>
> *Cc:* es-discuss <es-discuss@mozilla.org>
> *Subject:* Re: Are thrown errors in a try block considered to be handled
> even if there's no catch block?
>
>
>
> > Are thrown errors in a try block considered to be handled
>
> > even if there's no catch block?
>
>
>
> An exception propagates out of a function (and thus is ultimately reported
> unhandled if unhandled) if it's what terminates the function. If code in
> the `finally` block does something to prevent the original exception
> terminating the function (by continuing a loop within the function,
> returning something, throwing a different exception, etc.), then the
> (original) exception doesn't propagate.
>
>
>
> > If you swap out the catch block for a finally block (with either
>
> > `continue` or some kind of recursive iteration), the errors
>
> > aren't technically handled, but only that last one is
>
> > considered "uncaught".
>
>
>
> The last one will only be special if you treat it differently from the
> previous ones. I *think* you mean something like this:
>
>
>
> ```js
>
> for (let i = 0; i < 3; ++i) {
>
> try {
>
> throw i; // E.g., code that may throw
>
> } finally {
>
> if (i < 2) { // If we're not on the last iteration
>
> continue;
>
> }
>
> }
>
> }
>
> ```
>
>
>
> There, by using `continue` in the `finally` block (for all but the last
> one), we're preventing the exception from propagating because we've changed
> the completion of the block from 'throw' to 'continue', details:
>
>
>
> * [The `continue` statement - Runtime semantics - Evaluation][1]
>
> * [The `try` statement - Runtime semantics - Evaluation][2]
>
> * and the various loop definitions, for instance [The `for` statement -
> Runtime semantics - ForBodyEvaluation][3].
>
>
>
> I think that's the answer to your question about `finally`.
>
>
>
> The core issue you're having, replicating `dispatchEvent`'s behavior, is
> fascinating; I don't think you can do what it does (at least, what it does
> on Chrome), because it calls the handlers *synchronously*, allowing their
> exceptions to propagate (synchronously), but also continuing its
> synchronous loop through the handlers. I found the results of this code
> fascinating, for instance (https://jsfiddle.net/krdqo1kw/):
>
>
>
> ```js
>
> Promise.resolve().then(_ => console.log("then"));
>
> const target = document.createElement('div');
>
> target.addEventListener('foo', e => {
>
> console.log("1");
>
> throw 1;
>
> });
>
> target.addEventListener('foo', e => {
>
> console.log("2; cancelling");
>
> e.stopImmediatePropagation();
>
> throw 2;
>
> });
>
> target.addEventListener('foo', e => {
>
> console.log("3");
>
> throw 3;
>
> });
>
> target.dispatchEvent(new CustomEvent('foo', {cancelable: true}));
>
> console.log("dispatch complete");
>
> ```
>
>
>
> On Chrome, I get:
>
>
>
> ```
>
> 1
>
> Uncaught 1
>
> 2; cancelling
>
> Uncaught 2
>
> dispatch complete
>
> then
>
> ```
>
>
>
> ...where the uncaught exception traces point to the `throw` line in the
> relevant event handler. Very nice. Note the synchronous processing. I
> should dive into the source, but clearly it's creating a job and running it
> synchronously (or code to that effect), and since the exceptions aren't
> handled by anything in the job, they get reported as unhandled.
>
>
>
> On Firefox, I get
&

Re: Are thrown errors in a try block considered to be handled even if there's no catch block?

2017-06-23 Thread Andy Earnshaw
 {
> const exceptions = [];
> const event = {cancel: false};
> for (const f of this.subscribers) {
> try {
> f(event);
> } catch (e) {
> exceptions.push(e);
> }
> if (event.cancel) {
> break;
> }
> }
> for (const e of exceptions) {
> setTimeout(_ => { throw e; }, 0);
> }
> }
> }
> const target = new Publisher();
> target.subscribe(e => {
> console.log("1");
> throw 1;
> });
> target.subscribe(e => {
> console.log("2; cancelling");
> e.cancel = true;
> throw 2;
> });
> target.subscribe(e => {
> console.log("3");
> throw 3;
> });
> target.trigger();
> Promise.resolve().then(_ => console.log("then"));
> ```
>
> On Chrome, those traces point to our `setTimeout` line; on Firefox, they
> don't have a source. Not really ideal we have to wait for the next
> macrotask to report the exceptions, but it lets us run the handlers
> efficiently while still getting the engine to report the unhandled
> exceptions in its usual way. (Using `Promise.resolve().then(_ => { throw e;
> })` would at least put them on the task's microtask queue, but it would
> mean they'd be reported as unhandled rejections rather than unhandled
> exceptions.)
>
> I can't see how to replicate Chrome's behavior though.
>
> -- T.J. Crowder
>
> [1]:
> https://tc39.github.io/ecma262/#sec-continue-statement-runtime-semantics-evaluation
> [2]:
> https://tc39.github.io/ecma262/#sec-try-statement-runtime-semantics-evaluation
> [3]: https://tc39.github.io/ecma262/#sec-forbodyevaluation
>
> On Fri, Jun 23, 2017 at 10:20 AM, Andy Earnshaw <andyearns...@gmail.com>
> wrote:
>
>> A long trip down a rabbit hole has brought me here. Long story
>> short(ish), I was attempting to replicate how
>> `EventTarget.prototype.dispatchEvent()` works in plain JavaScript code. A
>> naive implementation (like Node's EventEmitter) would simply loop over any
>> bound handlers and call them in turn.  However, this isn't very robust
>> because one bound handler can prevent the rest from executing if it throws.
>>
>> DOM's dispatchEvent() doesn't have this problem.  Consider the following
>> code:
>>
>> ```
>> target = document.createElement('div');
>> target.addEventListener('foo', () => { throw 1; });
>> target.addEventListener('foo', () => { throw 2; });
>> target.addEventListener('foo', () => { throw 3; });
>> target.dispatchEvent(new CustomEvent('foo'));
>> ```
>>
>> If executed in a browser, I see:
>>
>> > Uncaught 1
>> > Uncaught 2
>> > Uncaught 3
>>
>> Even though each one throws, they all still execute.  In our naive
>> implementation, if you wrap each callback with a try/catch, errors thrown
>> become handled, so the callback provider might not be aware of errors or it
>> may be difficult to debug them without a stack trace. Global error handlers
>> aren't triggered either.  If you swap out the catch block for a finally
>> block (with either `continue` or some kind of recursive iteration), the
>> errors aren't technically handled, but only that last one is considered
>> "uncaught".
>>
>> I've observed this behaviour in current versions of Chrome, Firefox and
>> Safari.  Does that mean the spec defines finally blocks to behave this way,
>> or is it just an implementation-dependant behaviour they've all converged
>> on?
>>
>> PS I realise that dispatchEvent's behaviour stems from it creating a new
>> job for each handler function.  Interestingly, you can achieve something
>> similar in browsers by appending a new script element per handler function
>> to call it.  Not great for performance or achieving this transparently, but
>> it works as a sort of proof-of-concept.
>>
>> ___
>> 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


Are thrown errors in a try block considered to be handled even if there's no catch block?

2017-06-23 Thread Andy Earnshaw
A long trip down a rabbit hole has brought me here. Long story short(ish),
I was attempting to replicate how `EventTarget.prototype.dispatchEvent()`
works in plain JavaScript code. A naive implementation (like Node's
EventEmitter) would simply loop over any bound handlers and call them in
turn.  However, this isn't very robust because one bound handler can
prevent the rest from executing if it throws.

DOM's dispatchEvent() doesn't have this problem.  Consider the following
code:

```
target = document.createElement('div');
target.addEventListener('foo', () => { throw 1; });
target.addEventListener('foo', () => { throw 2; });
target.addEventListener('foo', () => { throw 3; });
target.dispatchEvent(new CustomEvent('foo'));
```

If executed in a browser, I see:

> Uncaught 1
> Uncaught 2
> Uncaught 3

Even though each one throws, they all still execute.  In our naive
implementation, if you wrap each callback with a try/catch, errors thrown
become handled, so the callback provider might not be aware of errors or it
may be difficult to debug them without a stack trace. Global error handlers
aren't triggered either.  If you swap out the catch block for a finally
block (with either `continue` or some kind of recursive iteration), the
errors aren't technically handled, but only that last one is considered
"uncaught".

I've observed this behaviour in current versions of Chrome, Firefox and
Safari.  Does that mean the spec defines finally blocks to behave this way,
or is it just an implementation-dependant behaviour they've all converged
on?

PS I realise that dispatchEvent's behaviour stems from it creating a new
job for each handler function.  Interestingly, you can achieve something
similar in browsers by appending a new script element per handler function
to call it.  Not great for performance or achieving this transparently, but
it works as a sort of proof-of-concept.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: How about awaiting Arrays ?

2017-03-03 Thread Andy Earnshaw
On Fri, 3 Mar 2017 at 16:51 Michał Wadas  wrote:

> Actually I would go with
>
> await ...expr;
>
I think `await.all` is clearer and more explicit, and await.race could be
added too.

Also: here's previous discussion that didn't go anywhere:
https://esdiscuss.org/topic/proposal-await-p1-p2-equivalent-to-await-promise-all-p1-p2
.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Enable async/await to work on functions that don't just return promises.

2017-02-27 Thread Andy Earnshaw
I had a similar thought a while ago for adapting non-promise functions, by
way of `async.resolve()` and `async.reject()`:

```javascript
async function asyncFunction() {
someAsync('data', (err, data) => {
if (err) async.reject(err);
async.resolve(data);
})
}
```

This differs from your proposal in that it's more explicit.  Neither really
give much benefit beyond saving a few bytes of code, probably not worth the
extra complexity.  It might be ok as an API, e.g. Promise.adapt(someAsync),
but the downside there is that it can't be very generic (an argument could
be made for the very common Node callback pattern where the last argument
to the function is the callback and the params are always err, result).

There are also existing NPM libraries to "promisify" module exports.

On Mon, 27 Feb 2017 at 08:42 Isiah Meadows  wrote:

> May I add one more thing: the main topic this was about is adapting
> non-standard async APIs (like Node's error-first callback idiom) to the
> land of promises. Async functions and iterators are incredibly useful when
> you're dealing with just promises, especially consuming them, but this is
> about creating promise adapters, not consuming promises.
>
> On Sun, Feb 26, 2017, 18:52 Mark  wrote:
>
> Codefined, just out of curiousity, do you have anything to do with this
> proposal that got announced today
> ? Or is it just a coincidence?
> :)
> ​
>
> On Sun, Feb 26, 2017 at 3:07 PM Dean Tribble  wrote:
>
> Should `callee()` be asynchronous here?  To my mind, no, it shouldn't.
> Every single line here is synchronous, so the function itself should surely
> be synchronous.  Shouldn't functions that may not have `await` in them, but
> instead that are actually asynchronous and hence use the `async return`
> keyword be the ones we define with `async`?
>
>
> In the Javascript (and Midori) model, concurrent execution of multiple
> activities is achieved by breaking those activities up into coarse-grained,
> application-defined "turns" (or "jobs") and interleaving those.  An async
> boundary is where the current turn could end, and the turns for other
> concurrent activities might run, changing the state before the current
> activity proceeds.
>
> Therefore, callee must be async, because that declares that there could
> be a turn boundary within it, and thus, the rest of the state of the
> program could change as a result of the call.  The caller of callee *must
> *ensure that it's invariants are correct before allowing other code to
> interleave with it.
>
> ___
> 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: Ranges

2016-12-14 Thread Andy Earnshaw
I think you'd be lucky to even get to that stage.  Vendors aren't keen on
any kind of backwards incompatibility in new specs and trying to get this
to stage 4 with such a glaring one would be practically  impossible.

It's not just the incompatibility either.  You also introduce an
inconsistencies where things like `[1..toFixed(2)]` doesn't mean the same
as `[ 1..toFixed(2) ]`. That kind of thing is just confusing to developers.

When you consider these things, it becomes clear that it's not practical to
change the language this way for such a small benefit.

On Wed, 14 Dec 2016, 03:00 Hikaru Nakashima, 
wrote:

> Oh, I understood it.
> It looks like serious problem, but it is may not actually.
> If this spec change doesn't break web, we can introduce this idea?
> ___
> 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: Ranges

2016-12-11 Thread Andy Earnshaw
On Thu, 3 Nov 2016 at 22:11 Zach Lym  wrote:

> With regard to syntax, Rust's is the best that I've seen: '0 ... 10'
> inclusive and  '1 .. 9' exclusive.
>

I love Rust's syntax too, but unfortunately 1.. is already valid
ES syntax:

1..Infinity
//-> undefined

Number.prototype.foo = 'bar'
1..foo
//-> 'bar'

You'd have to enforce the spaces around the operator, which would be weird
IMO.  `...` would be ok though.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: anaphoric if and while syntax

2016-09-15 Thread Andy Earnshaw
The main barrier that I can see is that this requires new semantics.  At
the moment, variable declarations don't have any kind of usable result.  If
you consider

let a = eval('let b = 1');
console.log(a);
//-> undefined

This sounds like an easy thing to solve, but how about this:

if (let a = foo(), b = bar()) {
}

Does the block execute if `a` and `b` are both truthy, or just `b`?  My gut
instinct says "if bar() is truthy", but it still seems awkward.  Any option
might be confusing depending on your level of experience.   What about this:

if (let { a, b } = foo) {
}

Does the block execute if `a` and `b` are both truthy, just `b`, or if
`foo` is truthy?  I'd lean towards `foo` in this case, but I think it looks
pretty bad and I'd hate to see it in code.  It might make more sense to
throw for destructuring or if there's more than one assignment.

On Tue, 13 Sep 2016 at 01:32 Danielle McLean 
wrote:

> In current ECMAScript, it is legal to place a variable declaration inside
> the
> initialiser of a `for` loop, as well as to declare the variable used by a
> `for...in` or `for...of` loop within the declaring expression:
>
> for (let i = 0; i < 5; ++i) console.log(i);
> for (let item of collection) process(item);
>
> When this syntax is used with `let` or `const`, the resulting variable is
> scoped to the loop and is not visible to the rest of the surrounding block.
>
> I propose that this syntax be extended, making it legal to place a variable
> declaration within the condition of an `if` or `while` statement. Any
> truthy
> value will cause the `if` block to run or `while` loop to repeat, as usual
> -
> the advantage is that the particular truthy value is bound to a variable
> and
> can be used inside the conditional block. For example, here is the
> situation
> that prompted my writing this proposal:
>
> if (const oldValue = _.get(object, 'some.long.path')) {
>   object.some.long.path = transform(oldValue);
> }
>
> As with the existing behaviour of declarations inside `for`, variables
> declared
> using `let` or `const` would be scoped to the individual `if` or `while`
> statement, rather than the containing block. In other words, the above
> syntax
> would be equivalent to the following currently-valid form I ended up
> writing:
>
> {
>   const oldValue = _.get(object, 'some.long.path');
>   if (oldValue) object.some.long.path = transform(oldValue);
> }
>
> Another use case which C aficianados might recognise:
>
> while (const c = getchar()) {
> process(c);
> }
>
> This syntax is already legal in C++, although not in C - in general this
> support is known as "anaphoric if", as it allows the body of the statement
> to
> refer back to the condition value. It's especially helpful in languages
> with
> truthiness, which ECMAScript has, as it allows access to the *specific*
> truthy
> value without further finagling.
>
> Thoughts?
> ___
> 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: anaphoric if and while syntax

2016-09-15 Thread Andy Earnshaw
How so? Assignment is already possible in control structures.  I think this
reads better:

```
if (let a = foo) {
```

Than:

```
let a;

//...

if (a = foo) {
```

Having the `let` or `const` inside the conditional part clarifies the
intent. There's an argument for not doing assignment inside the conditional
part, but it's subjective and people will write code that way regardless.
I'd much rather see `let` or `const` next to code like that if it means
mistakes are less likely to be made.

On Thu, 15 Sep 2016, 15:17 Mark Volkmann,  wrote:

> For what it's worth, I'm on the side of people that do not want to see
> assignment statements in control structures. I don't think it is necessary
> and it results in code that is harder to read.
>
> On Wed, Sep 14, 2016 at 8:51 PM, Alan Johnson  wrote:
>
>> What about `else if`?
>>
>> On Sep 14, 2016 9:28 PM, "Bergi"  wrote:
>>
>>> Danielle McLean wrote:
>>>
>>> variables declared
 using `let` or `const` would be scoped to the individual `if` or `while`
 statement, rather than the containing block. In other words, the above
 syntax
 would be equivalent to the following currently-valid form I ended up
 writing:

 {
   const oldValue = _.get(object, 'some.long.path');
   if (oldValue) object.some.long.path = transform(oldValue);
 }

>>>
>>> What about `else` blocks, would the variables be available in them as
>>> well?
>>>
>>> - Bergi
>>>
>>> ___
>>> 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
>>
>>
>
>
> --
> R. Mark Volkmann
> Object Computing, Inc.
> ___
> 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: Function constants for Identity and No-op

2016-08-10 Thread Andy Earnshaw
On Wed, 10 Aug 2016 at 12:42 Michał Wadas  wrote:

> Function.prototype is no-op (run Function.prototype.toString() for more
> information)
>

That's true, but using `Function.prototype` can be confusing when passed to
a function as a callback:

someFunc(Function.prototype);

It's not immediately clear that `someFunc` is expecting a callback function
in this case, whereas `Function.NOOP` or `() => {}` are pretty obvious.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Oddly accepted RegExps

2016-06-03 Thread Andy Earnshaw
IE has supported all of these for as long as I can remember.  AFAIK, it's
never been a requirement _in browsers_ to escape [ inside a character class
or ] outside e.g. `/[[]/` ([ is inside) or `/[]]/` (] is outside).  If it's
not the case in the spec (I haven't checked the spec grammar), it should
probably be classed as  a spec bug for compat reasons.

On Fri, 3 Jun 2016 at 14:20 Boris Zbarsky  wrote:

> On 6/3/16 4:20 AM, Isiah Meadows wrote:
> > These three RegExps don't appear valid, even after reading the Annex B,
> > but they do behave consistently in both Chrome and Firefox.
>
> Note that Chrome and Firefox use the same regexp implementation, so them
> agreeing on how a regexp is handled means a lot less than if two
> independent implementations agreed.
>
> -Boris
> ___
> 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: How about a "named true" and a "named true property"

2016-05-26 Thread Andy Earnshaw
This is more a problem to be solved in API design and if you see such a
method being introduced to libraries or specifications, you should raise
your concerns with the author(s).  Fortunately, Ecma-262 seems to avoid
this pitfall by accepting objects-as-dictionaries, and most newer web APIs
seem to be trending towards the same thing.  Even jQuery has made an effort
to do the same[1].

You don't even need to use variables to avoid the boolean trap in
third-party APIs, you can simply use strings:

$.clone(sourceObject, !!'deep'); // true
$.clone(sourceObject, !'deep'); // false

This is more akin to the your `:removeNode` example and is something that a
minifier or engine may optimise for you.

[1]: https://bugs.jquery.com/ticket/13103

On Thu, 26 May 2016 at 10:35 Oriol Bugzilla 
wrote:

> As Isiah Meadows said, you can just use variables.
>
> ```
> var removeNode = true;
> control.dispose(removeNode);
> ```
>
> ```
> var silent = true,
>   disableValidation = true,
>   destroyOldValue = false;
> model.set('foo', newValue, {silent, disableValidation, destroyOldValue});
> ```
>
> --
> From: otakus...@gmail.com
> Date: Thu, 26 May 2016 09:02:21 +
> Subject: How about a "named true" and a "named true property"
> To: es-discuss@mozilla.org
>
>
> I don't really know how to name this feature, but I find it quite
> neccessary
>
> In JavaScript land there are many functions with parameters of type
> boolean, and invocations to these functions do not have high readability,
> for example jQuery have a `clone` method with a parameter deep of type
> boolean, but when read a code like:
>
> ```
> $.clone(sourceObject, true);
> ```
>
> it's hard to understand what is that `true` stands for, a more unfamiliar
> API could make this more uncomfortable:
>
> ```
> control.dispose(true); // does it mean "to remove DOM node or anything
> else?"
> ```
>
> In practice we can write some comment after a boolean parameter to explain
> what it is:
>
> ```
> control.dispose(true /* removeNode */);
> ```
>
> but it's a lot of work.
>
> In this case I think we may introduce a handy syntax called "named true"
> which only transforms to the keyword `true` but have a custom name:
>
> ```
> control.dispost(:removeNode);
> ```
>
> Here a leading colon hints it is a "named true" so in parsing stage
> `:removeNode` simply becomes `true`, and we can have a false value with
> simply `!:removeNode`, it doesn't hit performance but notably increase
> readability
>
> Boolean parameters is not good practice but I believe it is
> not eliminated nowadays and will never be eliminated, so a more friendly
> syntax could save a lot of time
>
> ---
>
> Furthermore, there are also many functions accepting an `options`
> parameter including some "flag properties", flag properties are simple
> properties with a boolean value, a good example is the {silent: true} flag
> in many event related APIs.
>
> Constructing an `options` object containing flag properties are not easy,
> we may repeat `: true` and `: false` many times, so with previously "named
> true", I think a "named true property" could help to save time:
>
> ```
> model.set('foo', newValue, {:silent, :disableValidation,
> !:destroyOldValue})
> ```
>
> Here `:silent` is simply parsed to `silent: true` and `!:destroyOldValue`
> is for `destroyOldValue: false`, it can save a large amount of code
>
> All syntax here are just examples, not any propose to grammar
>
> ___ 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: AND and OR in if statement

2016-05-25 Thread Andy Earnshaw
It's not feasible anyway because AND and OR are already valid identifiers:

a = foo()
  &&(bar)

is equivalent to `a = foo() && bar`, but

a = foo()
  AND(bar)

is equivalent to

a = foo();
AND(bar);

On Wed, 25 May 2016 at 02:29 kdex  wrote:

> Could you explain how your second example is cleaner? All I see is that
> it's longer; the rest is merely a matter of taste.
> JavaScript's syntax was, amongst others, heavily influenced by C-family
> languages (which went for `&&` and `||` as well as `&` and `|`).
>
> Next, I think it's confusing that, although we're calling it "bitwise and"
> and "bitwise or", we would only be able to write `and` or `or` in a logical
> context; this choice is entirely arbitrary. Bitwise operators would still
> need to be `&` and `|` since there's no way to tell what your intent is
> just from the syntax.
>
> IMHO, the current operators `&&`, `&`, `||` ,`|` are the cleanest
> implementation of `and` and `or` that I could think of.
>
> On Dienstag, 24. Mai 2016 21:14:59 CEST Francis Clavette wrote:
> > Hi,
> > I’d like to be able to use AND for && and OR for || in conditional
> statements in a future version of ECMAScript. It’s a feature I’ve always
> been wanting since transitioning from PHP. It’s also much cleaner :
> >
> > if ($scope.newSourceModal.isShown() && $scope.newsource.type == "book"
> && (!$scope.insertingFromScan || $scope.ok))
> >
> > ==
> >
> > if ($scope.newSourceModal.isShown() AND $scope.newsource.type == "book"
> AND (!$scope.insertingFromScan OR $scope.ok))
> >
> >
> > Francis
> >
> ___
> 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: extending an ES6 class using ES5 syntax?

2016-05-14 Thread Andy Earnshaw
FWIW the warning is going away.
https://bugzilla.mozilla.org/show_bug.cgi?id=1049041

On Sat, 14 May 2016, 20:25 Boris Zbarsky,  wrote:

> On 5/14/16 3:11 AM, Andrea Giammarchi wrote:
> >  1. why is that?
>
> Why does mutating the proto after an object has been exposed to script
> end up deoptimizing things?  Because it invalidates assumptions JITs
> otherwise make.  So the options are to make the
> proto-hasn't-been-mutated case slower by not making those assumptions or
> to make the proto-has-been-mutated case slower.  Guess which one is a
> better choice?
>
> > There is a
> > spec'd method that is not even on Annex B and Firefox deliberately
> > discourage its usage.
>
> Sure.  Just because something specced doesn't mean it's a good idea to
> actually do it.
>
> This is why in the HTML spec there's all sorts of stuff that's marked as
> "not valid HTML" for authoring purposes even though the spec then goes
> ahead and defines what a browser should do with that stuff if authors do
> it anyway.
>
> > Why I don't see warnings every time I
> > `[].slice.call(arguments)`?
>
> Because that's not as big a performance hit?
>
> > I understand it might de-optimize but I
> > wonder if that's really always necessary (maybe it doesn't have to
> > deopt if it's a well known operation with a predictable result).
>
> I'm not an expert on the type inference setup (which is what ends up
> deoptimizing on proto mutation, iirc), so I can't usefully answer this.
>
> > On the other side, I also wish Firefox woudn't show warnings about
> > modern and recent specifications. Deprecated stuff is OK,
>
> There can totally be things that are both recently added to the spec
> (for UA implementation purposes, because everyone has to do it for web
> compat) and deprecated for authoring purposes (because they're a bad
> idea).  Dynamic proto mutation is one of those.  ;)
>
> >  2. where were you when the `__proto__` landed on specs? :P
>
> You mean when every browser on the market implemented it, which was the
> relevant bit?  The addition to the spec was just acknowledging ugly
> reality.
>
> Where was I when browsers implemented __proto__?  We're talking 20ish
> years ago, so probably high school or a few years into college.
>
> -Boris
> ___
> 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: JavaScript Language feature Idea

2016-04-18 Thread Andy Earnshaw
I assume if you were to spec out the additional syntax you'd go the whole
hog and add ranges, e.g.

arr[:-4, -2];

Like I said, not particularly compelling as it's not a huge saving over
slice() and selecting single negative indices can be done with Proxy.

On Mon, 18 Apr 2016 20:32 Michael Theriot, <michael.lee.ther...@gmail.com>
wrote:

> This can be trivially done with proxies. I don't think arrays should have
> a special trap dependent on whether or not a symbol is set. If I were to
> make a custom array with proxies I would then have to check if someone
> changed standard behavior by inserting a symbol, and pass the symbol to the
> target just to work properly.
>
> If the `var arr = [1,2,3];` syntax is the real reason to change default
> behavior then just use `Array.from` like such `var arr =
> InvertedArray.from([1,2,3]);`. See below...
>
> ```
> var getProp = (target, property) => typeof property !== 'symbol' &&
> target.length && property < 0 && property >= -target.length ? +property +
> target.length : property;
>
> var handler = {
>   get: (target, property, receiver) => Reflect.get(target, getProp(target,
> property), receiver),
>   set: (target, property, value, receiver) => Reflect.set(target,
> getProp(target, property), value, receiver)
> };
>
> var InvertedArray = new Proxy(function InvertedArray(arg1) {}, {
>   construct: (target, arguments, newTarget) => new
> Proxy(Reflect.construct(Array, arguments, InvertedArray), handler)
> });
>
> Reflect.setPrototypeOf(InvertedArray, Array);
>
> InvertedArray.prototype = Object.create(Array.prototype);
> ```
>
> Arrays are effectively regular objects with traps on get/set to update the
> length property. I don't think they should have a special new syntax to
> access negative indices like `arr[:-1]` since it would logically have to
> work on all objects and is dependent on a length property; it's just
> syntactic sugar for yet another trap.
>
> On Mon, Apr 18, 2016 at 2:05 PM, kdex <k...@kdex.de> wrote:
>
>> `Symbol.implementation` should be fairly trivial to implement once
>> [Realm](https://github.com/caridy/proposal-realms)s are around, without
>> affecting global scope.
>>
>> On Montag, 18. April 2016 18:58:06 CEST Andy Earnshaw wrote:
>> > I don't think that would be trivial to implement and there might not be
>> a
>> > common enough use case for it.  You might want to look into something
>> like
>> > http://sweetjs.org if it's the syntactic sugar you're looking for.
>> >
>> > On Mon, 18 Apr 2016 19:35 /#!/JoePea, <j...@trusktr.io> wrote:
>> >
>> > > > ```js
>> > > > Array[Symbol.implementation] = MyArray;
>> > > > ```
>> > >
>> > > > That would mean all other programs executing on the page would be
>> forced
>> > > to use that Array implementation
>> > >
>> > > And also with my suggestion that would impact all code too.
>> > >
>> > > Would it be possible to limit the effect of using certain symbols to a
>> > > scope where the symbol is used? For example:
>> > >
>> > > ```js
>> > > function main() {
>> > >   Array[Symbol.implementation] = MyArray;
>> > >
>> > >   let a = [1,2,3] // uses MyArray
>> > > }
>> > > let a = [1,2,3] // uses Array
>> > > main()
>> > > ```
>> > >
>> > > or
>> > >
>> > > ```js
>> > > Array[Symbol.implementation] = MyArray;
>> > > function main() {
>> > >   let a = [1,2,3] // uses MyArray, from outer scope
>> > > }
>> > > let a = [1,2,3] // uses MyArray
>> > > main()
>> > > ```
>> > >
>> > > Or maybe some other method on a per-scope basis?
>> > >
>> > > On Mon, Apr 18, 2016 at 11:25 AM, Andy Earnshaw <
>> andyearns...@gmail.com>
>> > > wrote:
>> > > > That would mean all other programs executing on the page would be
>> forced
>> > > to
>> > > > use that Array implementation, imposing potentially critical
>> problems
>> > > with,
>> > > > for example, performance and expected behavior. It's just not a good
>> > > idea.
>> > > >
>> > > > I missed off esdiscuss when I replied earlier, but I mentioned that
>> the
>> > > only
>> > > > reasonable solution is to introduce new syntax, e.g.
>> > > >
>> > > 

Re: JavaScript Language feature Idea

2016-04-18 Thread Andy Earnshaw
I don't think that would be trivial to implement and there might not be a
common enough use case for it.  You might want to look into something like
http://sweetjs.org if it's the syntactic sugar you're looking for.

On Mon, 18 Apr 2016 19:35 /#!/JoePea, <j...@trusktr.io> wrote:

> > ```js
> > Array[Symbol.implementation] = MyArray;
> > ```
>
> > That would mean all other programs executing on the page would be forced
> to use that Array implementation
>
> And also with my suggestion that would impact all code too.
>
> Would it be possible to limit the effect of using certain symbols to a
> scope where the symbol is used? For example:
>
> ```js
> function main() {
>   Array[Symbol.implementation] = MyArray;
>
>   let a = [1,2,3] // uses MyArray
> }
> let a = [1,2,3] // uses Array
> main()
> ```
>
> or
>
> ```js
> Array[Symbol.implementation] = MyArray;
> function main() {
>   let a = [1,2,3] // uses MyArray, from outer scope
> }
> let a = [1,2,3] // uses MyArray
> main()
> ```
>
> Or maybe some other method on a per-scope basis?
>
> On Mon, Apr 18, 2016 at 11:25 AM, Andy Earnshaw <andyearns...@gmail.com>
> wrote:
> > That would mean all other programs executing on the page would be forced
> to
> > use that Array implementation, imposing potentially critical problems
> with,
> > for example, performance and expected behavior. It's just not a good
> idea.
> >
> > I missed off esdiscuss when I replied earlier, but I mentioned that the
> only
> > reasonable solution is to introduce new syntax, e.g.
> >
> > myArray[:-1]
> >
> > However, it's been said that there needs to be a compelling reason to add
> > new syntax and I'm not sure this qualifies imo.
> >
> >
> > On Mon, 18 Apr 2016 19:11 kdex, <k...@kdex.de> wrote:
> >>
> >> Yes, now we're heading in the right direction.
> >>
> >> The problem with something like `Symbol.propertyAccess` is that this
> might
> >> lead to a flood of new well-known Symbols.
> >> Conceptually, `Symbol.propertyAccess` sounds like it should have been a
> >> `Proxy` trap, anyway.
> >>
> >> Here's an more general idea: Why not allow users to set a derived class
> >> for literals via well-known Symbols?
> >> Thus, users could provide custom implementations for `RegExp`, `Array`,
> >> `Object` (…) literals, as long as the value points to a derived class.
> >>
> >> We could even introduce negative array indices in a way that doesn't
> break
> >> the web like this:
> >>
> >> ```js
> >> [1, 2, 3][-1]; // undefined
> >> Array[Symbol.implementation] = MyArray;
> >> [1, 2, 3][-1]; // 3
> >> Array[Symbol.implementation] = 3; // TypeError: Array implementations
> must
> >> extend Array (→ Array.isPrototypeOf(Number(3)) is false)
> >> ```
> >>
> >> On Montag, 18. April 2016 10:47:24 CEST /#!/JoePea wrote:
> >> > But, can
> >> >
> >> > ```js
> >> > let a = [1,2,3]
> >> > ```
> >> >
> >> > create a new MyArray? Maybe, instead of having negative indices by
> >> > default (which breaks some backwards compatibility) we can introduce a
> >> > symbol for overriding property access? Something like
> >> >
> >> > ```js
> >> > Array.prototype[Symbol.propertyAccess] = function(index) {
> >> >   if (index < 0) ...
> >> >   else ...
> >> > }
> >> > ```
> >> >
> >> > ? Just an idea; I'm not sure if that's a good use for Symbols. We
> >> > could then easily add this helper code to a given app.
> >> >
> >> > On Mon, Apr 18, 2016 at 10:25 AM, kdex <k...@kdex.de> wrote:
> >> > > I don't see a good reason why to mangle with this.
> >> > > Note that you can achieve this behavior without breaking backwards
> >> > > compatibility with ES6 Proxies:
> >> > >
> >> > > ```js
> >> > > class MyArray extends Array {
> >> > > constructor(...args) {
> >> > > super(...args);
> >> > > function computeProperty(target, property) {
> >> > > const index = +property;
> >> > > return index < 0 ? String(target.length +
> >> > > index) : property;
> >> > > }
> >> > >  

Re: JavaScript Language feature Idea

2016-04-18 Thread Andy Earnshaw
That would mean all other programs executing on the page would be forced to
use that Array implementation, imposing potentially critical problems with,
for example, performance and expected behavior. It's just not a good idea.

I missed off esdiscuss when I replied earlier, but I mentioned that the
only reasonable solution is to introduce new syntax, e.g.

myArray[:-1]

However, it's been said that there needs to be a compelling reason to add
new syntax and I'm not sure this qualifies imo.

On Mon, 18 Apr 2016 19:11 kdex,  wrote:

> Yes, now we're heading in the right direction.
>
> The problem with something like `Symbol.propertyAccess` is that this might
> lead to a flood of new well-known Symbols.
> Conceptually, `Symbol.propertyAccess` sounds like it should have been a
> `Proxy` trap, anyway.
>
> Here's an more general idea: Why not allow users to set a derived class
> for literals via well-known Symbols?
> Thus, users could provide custom implementations for `RegExp`, `Array`,
> `Object` (…) literals, as long as the value points to a derived class.
>
> We could even introduce negative array indices in a way that doesn't break
> the web like this:
>
> ```js
> [1, 2, 3][-1]; // undefined
> Array[Symbol.implementation] = MyArray;
> [1, 2, 3][-1]; // 3
> Array[Symbol.implementation] = 3; // TypeError: Array implementations must
> extend Array (→ Array.isPrototypeOf(Number(3)) is false)
> ```
>
> On Montag, 18. April 2016 10:47:24 CEST /#!/JoePea wrote:
> > But, can
> >
> > ```js
> > let a = [1,2,3]
> > ```
> >
> > create a new MyArray? Maybe, instead of having negative indices by
> > default (which breaks some backwards compatibility) we can introduce a
> > symbol for overriding property access? Something like
> >
> > ```js
> > Array.prototype[Symbol.propertyAccess] = function(index) {
> >   if (index < 0) ...
> >   else ...
> > }
> > ```
> >
> > ? Just an idea; I'm not sure if that's a good use for Symbols. We
> > could then easily add this helper code to a given app.
> >
> > On Mon, Apr 18, 2016 at 10:25 AM, kdex  wrote:
> > > I don't see a good reason why to mangle with this.
> > > Note that you can achieve this behavior without breaking backwards
> compatibility with ES6 Proxies:
> > >
> > > ```js
> > > class MyArray extends Array {
> > > constructor(...args) {
> > > super(...args);
> > > function computeProperty(target, property) {
> > > const index = +property;
> > > return index < 0 ? String(target.length +
> index) : property;
> > > }
> > > return new Proxy(this, {
> > > get(target, property, receiver) {
> > > return Reflect.get(target,
> computeProperty(target, property), receiver);
> > > },
> > > set(target, property, receiver) {
> > > return Reflect.set(target,
> computeProperty(target, property), receiver);
> > > }
> > > });
> > > }
> > > }
> > > ```
> > >
> > > On Montag, 18. April 2016 09:59:15 CEST /#!/JoePea wrote:
> > >> Backwards compatibility has been broken before. I don't think this one
> > >> is too bad of a breakage.
> > >>
> > >> On Sun, Apr 17, 2016 at 9:48 PM, Biju  wrote:
> > >> > On 17 April 2016 at 17:29, Frankie Bagnardi 
> wrote:
> > >> >> That would break backward compatibility;
> > >> >>
> > >> >> ```js
> > >> >> var a = ['a'];
> > >> >> a['-1'] = 'test';
> > >> >> Object.keys(a) // ['0', '-1']
> > >> >> ```
> > >> >
> > >> > Do we have statistics how many sties depend on that?
> > >> > ___
> > >> > 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
>
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Function#toString revision: JSDoc comments?

2016-04-18 Thread Andy Earnshaw
I imagine there's code in the wild that predates function.name, looking
something like this:

var fooName = foo.toString().match(/^function (\w+)/)[1];

If a newer browser adds a preceding comment to the function then this code
will break.  The top voted answer to a question[1] on Stack Overflow would
break if the comment contained the string 'function '.

[1]: http://stackoverflow.com/q/2648293

On Sun, 17 Apr 2016 at 11:07 Isiah Meadows  wrote:

> I don't like the idea of including preceding comments in
> `Function.prototype.toString` itself on grounds it's harder to parse for
> other related reasons.
>
> As for anything including preceding comments, I'd be happy with something
> somewhat independent, as long as it's not requiring JSDoc to be parsed. Not
> that I have issues with that documentation format, but I don't think it
> should be in the spec itself.
>
> On Sat, Apr 16, 2016, 13:29 Jordan Harband  wrote:
>
>> As I see it, the primary purpose of the `Function#toString` proposal is
>> to document what browsers already do, and tighten it down so they can't
>> deviate further (which some browsers already have begun to do with "class",
>> for example).
>>
>> "Preceding comments" would be a very hard thing to specify without unduly
>> blessing an arbitrary documentation pattern, especially one that isn't
>> universally considered to be a good thing.
>>
>> Reflection methods on functions are certainly a potential separate
>> proposal, if you can make a compelling argument that it's a good idea to
>> reflect on functions in this manner.
>>
>> On Sat, Apr 16, 2016 at 9:42 AM, Marius Gundersen 
>> wrote:
>>
>>> Would it not be better to expose the names (and default values,
>>> destructurings, etc) of the function arguments using reflection? For
>>> example, Reflection.arguments(Math.max).then this method can return any
>>> JSDoc it is able to parse.
>>> On 16 Apr 2016 16:53, "Caitlin Potter"  wrote:
>>>
 How would that interact with angular.js' Function.prototype.toString
 parsing? Seems like doing that could break some content, even if it were
 useful

 On Apr 16, 2016, at 10:48 AM, Axel Rauschmayer 
 wrote:

 Regarding this proposal:
 https://github.com/tc39/Function-prototype-toString-revision

 Wouldn’t it make sense to include a preceding JSDoc-style comment in a
 function’s (or method’s) `[[SourceText]]` value? Conceptually it is a part
 of the function and it could be used to implement a REPL `help()` function.

 --
 Dr. Axel Rauschmayer
 a...@rauschma.de
 rauschma.de

 ___
 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
>>
> ___
> 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: rest parameters

2015-10-07 Thread Andy Earnshaw
Damn, forgot the reply-all button the first time.  Including the original
and reply here, plus my reply inline:

On Tue, 6 Oct 2015 at 19:05 Tab Atkins Jr. <jackalm...@gmail.com> wrote:

> On Mon, Oct 5, 2015 at 6:33 AM, Andy Earnshaw <andyearns...@gmail.com>
> wrote:
> > On Sat, 3 Oct 2015 at 00:27 Tab Atkins Jr. <jackalm...@gmail.com> wrote:
> >> A few examples of the ambiguity:
> >>
> >> function f1(...a, b, c) {print arguments}
> >> f1(1) // ([], 1, undefined) or ([], undefined, 1) ?
> >>
> >> function f2(...a, b="default") {print arguments}
> >> f2(1) // ([], 1) or ([1], "default") ?
> >>
> >> function f3(a, b, ...c, d, e) {print arguments)
> >> f3(1,2,3) // (1, 2, [], 3, undefined) or (1, 2, [], undefined, 3) or
> >> (1, undefined, [], 2, 3) or something else?
> >
> >
> > I don't think these are as ambiguous as you say.  For the first and third
> > case, the first possible result you mention in both cases seems pretty
> > natural.  I don't think you could make an argument for the other cases,
> they
> > don't really make any sense.
>
> Let me rename the arguments, then, to make it more obvious:
>
> function f1(...frontOfList, secondToLast, last) {print arguments;}
> f1(1)
> // (frontOfList=[], secondToLast=1, last=undefined)
> // or (frontOfList=[], secondToLast=undefined, last=1)?
>
> It would be difficult to argue, given these argument names, that the
> author intended the first result.  They clearly intended the second
> result.
>

Function arguments are always filled in from left to right, with the
proposed exception in this case being that rest params don't swallow passed
in arguments when arguments.length <= fn.length.  I don't think anyone
coming from a background in writing code would expect the second result,
any more than they would expect:

function f1 (first, last) { print arguments; }
f1(1);
// (first=undefined, last=1)

Unless there's a precedent for this behaviour in a language I'm unaware of.


> This is what I mean by:
>
> > You can come up with answers to these questions.  What you can't do is
> come up with answers that are *obviously correct*.
> ~TJ
>


> I don't know... the first result was "obviously correct" to me ;-).
Admittedly, "obviously correct" can be subjective when defining language
behaviour.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Any opinions about adding a Ruby-like ||= operator to EcmaScript?

2015-07-29 Thread Andy Earnshaw
Plenty of opinions about it here: https://esdiscuss.org/topic/is-much-needed
;-)

On Wed, 29 Jul 2015 at 12:23 Behrang Saeedzadeh behran...@gmail.com wrote:

 For example:

 obj.property ||= value;

 This would only assign value to obj.property if property is undefined or
 null.
 --
 Best regards,
 Behrang Saeedzadeh
 ___
 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: Unbound arrow functions?

2015-06-22 Thread Andy Earnshaw
The thing I liked about thin arrows (other than the conciseness) was the
lack of a prototype object, thus automatically throwing on construct and
having similar behaviour to native functions.  Concise methods and fat
arrows already have this behaviour, but if you want to add such a method to
an already existing object you have to resort to using Object.assign (or
have a function with a prototype that is made to throw on construct).

Of course, if we made .prototype configurable for non-builtins we could
always delete to get the same behaviour.  Not sure how viable that is, or
if it's worth it for such a minor convenience.

On Mon, 22 Jun 2015 at 01:07 Allen Wirfs-Brock al...@wirfs-brock.com
wrote:


 On Jun 21, 2015, at 7:42 AM, Erik Arvidsson wrote:

 At one point in time we allowed concise bodies in classes and object
 literals but the commas in object literals made the syntax problematic.

 We also talked about the possibility of allow ;  as an alternate separator
 in object literals.  But it didn't find much traction.

 Allen
 ___
 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: Should `use strict` be a valid strict pragma?

2015-02-05 Thread Andy Earnshaw
I think you're missing the point Leon is trying to make.  He's saying that,
in ES 6 we have a new way to write strings.  In some ways, these more
powerful strings may condition some people to use ` as their main string
delimiter.  An unsuspecting person may liken this to PHP's double quotes vs
single quotes, thinking that the only difference is that you can use
`${variable}` in strings that are delimited with backticks, but other than
that everything is the same.  When they write this in their code:

```
`use strict`;
```

They may introduce bugs by writing non-strict code that doesn't throw when
it should.  Adding it to the spec wouldn't be difficult and it would avoid
any potential confusion or difficult-to-debug issues.  It's definitely
easier than educating people, IMO.

On Thu, Feb 5, 2015 at 10:56 AM, Mathias Bynens math...@qiwi.be wrote:


  On 5 Feb 2015, at 11:04, Leon Arnott leonarn...@gmail.com wrote:
 
  Well, that isn't quite the full story - if it were just a case of
 pragmas having to use something, anything, that could pass ES3 engines,
 then there wouldn't necessarily be two otherwise-redundant forms of the
 syntax - `use strict` and `'use strict'`. The reason those exist is to
 save the author remembering which string delimiter to use - it mirrors the
 string literal syntax exactly.

 If that were the case, then e.g.
 `'\x75\x73\x65\x20\x73\x74\x72\x69\x63\x74'` would trigger strict mode. (It
 doesn’t, and that’s a good thing.)
 ___
 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: Should `use strict` be a valid strict pragma?

2015-02-05 Thread Andy Earnshaw
On 5 Feb 2015 15:06, Frankie Bagnardi f.bagna...@gmail.com wrote:

 I think any issues with that are imagined.  Languages have rules, and of
the people who both know what 'use strict' does and are using es6 syntax,
they're very unlikely to make the mistake.

Sure, it's theoretical at this point but not unimaginable. Eventually
everyone will be using es6 syntax, and there are plenty of blogs and
books around that explain the benefits of strict mode.

 I don't see people using template literals for arbitrary strings... it
could happen but it probably won't.

Not everyone, but I think it's likely that some will.  If you want to add a
variable ref to a static string, for instance, it's simpler if you don't
have to change the delimiters to back ticks. We can probably only speculate
right now.

 Mathias makes a good point also, it's not strings that equal the string
'use strict', it's exactly two possible arrangements of characters.

And that's obvious to us, but won't be to everyone. I'm on my phone right
now so it's hard to check, but I think you'll find more sources explaining
the directive is a string literal than you would an arrangement of
characters.

My immediate reaction was that it wasn't worth it, but I kinda think that
if it is easy enough to implement then any risk would be avoided by doing
so.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: descriptors and not only own properties gotcha

2014-12-18 Thread Andy Earnshaw
Can we be sure nobody's ever written something like this:

function shadow(obj, props) {
var ret = Object.create(obj);
}

On Thu, Dec 18, 2014 at 10:08 AM, Andrea Giammarchi 
andrea.giammar...@gmail.com wrote:

 My main point is that everything you get from
 `Object.getOwnPropertyDescriptor`, beside undefined or possible abrupt
 errors, will have own properties.

 Even es5-shim/sham has been checking own properties for years [1] so I am
 pretty confident nothing will break 'cause own properties is what
 developers always expected and what they've always used despite specs.

 Again it's clear the world can live with these possibly inherited
 descriptors properties but it feels very wrong on the practical level. Too
 bad if there won't be ever a fix [2]

 [1] https://github.com/es-shims/es5-shim/issues/211#event-208821479 now
 fixed

 [2] would a new Descriptor({ownproperties:only}) instance be ever
 considered ?



 On Wed, Dec 17, 2014 at 8:37 PM, Allen Wirfs-Brock al...@wirfs-brock.com
 wrote:


 On Dec 17, 2014, at 10:30 AM, Andrea Giammarchi wrote:

 Actually simplifying as proposal: does everyone agree that if a
 descriptor.[[Value]] is own property no further checks on inherited [[Get]]
 and [[Set]], or generally speaking Accessor Property related checks, should
 be made ?

 This would already fix the `Object.prototype.get` or `.set` case since I
 believe nobody ever used an inherited `value` property on purpose for
 descriptors ... or is it?

 It will keep `enumerable` and `writable` still potentially problematic
 but at least the following code would never fail:

 ```js
 Object.prototype.get = function () {}; Object.defineProperty(
 Object.prototype, 'toString', Object.getOwnPropertyDescriptor(
 Object.prototype, 'toString' ) );

 ```

 Thanks again for any sort of outcome (or clarification on when and if
 this will ever be fixed)


 I'm not sure what you are actually asking.  All specified internal uses
 of property descriptor objets should pas through ToPropertyDescriptor (
 http://people.mozilla.org/~jorendorff/es6-draft.html#sec-topropertydescriptor
 ) which will throw if there is any conflict between get/set and own
 value/writable properties, regardless of whether they are own or inherited.
  (If you know of any uses of such descriptor object in the ES6 spec that
 don't do this validation, please file a bug).

 If you want to enforce the same semantics on you ES-level uses of
 descriptor objects you need to write a ES level implementation of the
 checks performed by ToPropertyDescriptor.

 I can see various ways we might improve the specified processing of
 property descriptor objects but those would generally be breaking changes
 and we would have to consider the possible impact of such changes before
 proceeding with them.

 Allen


 ___
 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: descriptors and not only own properties gotcha

2014-12-18 Thread Andy Earnshaw
Oops, misfire.  The rest of that:

function shadow(obj, props) {
var ret = Object.create(obj);

for (var k in props)
ret[k] = props[k]

return ret;
}

// Elsewhere...
function defineSomeProps (obj) {
var defaults = { enumerable: true, writable: true, configurable:
true };

Object.defineProperties(obj, {
foo1: shadow(defaults, { value: 'bar1' })),
foo2: shadow(defaults, { value: 'bar2' })),
foo3: shadow(defaults, { value: 'bar3' })),
// etc...
});
}

If people have a generic shadow() function that creates an object and
copies properties to it (less verbosely than just using Object.create),
they could be tempted to use it to create ES3-style EWC properties.

On Thu, Dec 18, 2014 at 1:24 PM, Andy Earnshaw andyearns...@gmail.com
wrote:

 Can we be sure nobody's ever written something like this:

 function shadow(obj, props) {
 var ret = Object.create(obj);
 }

 On Thu, Dec 18, 2014 at 10:08 AM, Andrea Giammarchi 
 andrea.giammar...@gmail.com wrote:

 My main point is that everything you get from
 `Object.getOwnPropertyDescriptor`, beside undefined or possible abrupt
 errors, will have own properties.

 Even es5-shim/sham has been checking own properties for years [1] so I am
 pretty confident nothing will break 'cause own properties is what
 developers always expected and what they've always used despite specs.

 Again it's clear the world can live with these possibly inherited
 descriptors properties but it feels very wrong on the practical level. Too
 bad if there won't be ever a fix [2]

 [1] https://github.com/es-shims/es5-shim/issues/211#event-208821479 now
 fixed

 [2] would a new Descriptor({ownproperties:only}) instance be ever
 considered ?



 On Wed, Dec 17, 2014 at 8:37 PM, Allen Wirfs-Brock al...@wirfs-brock.com
  wrote:


 On Dec 17, 2014, at 10:30 AM, Andrea Giammarchi wrote:

 Actually simplifying as proposal: does everyone agree that if a
 descriptor.[[Value]] is own property no further checks on inherited [[Get]]
 and [[Set]], or generally speaking Accessor Property related checks, should
 be made ?

 This would already fix the `Object.prototype.get` or `.set` case since I
 believe nobody ever used an inherited `value` property on purpose for
 descriptors ... or is it?

 It will keep `enumerable` and `writable` still potentially problematic
 but at least the following code would never fail:

 ```js
 Object.prototype.get = function () {}; Object.defineProperty(
 Object.prototype, 'toString', Object.getOwnPropertyDescriptor(
 Object.prototype, 'toString' ) );

 ```

 Thanks again for any sort of outcome (or clarification on when and if
 this will ever be fixed)


 I'm not sure what you are actually asking.  All specified internal uses
 of property descriptor objets should pas through ToPropertyDescriptor (
 http://people.mozilla.org/~jorendorff/es6-draft.html#sec-topropertydescriptor
 ) which will throw if there is any conflict between get/set and own
 value/writable properties, regardless of whether they are own or inherited.
  (If you know of any uses of such descriptor object in the ES6 spec that
 don't do this validation, please file a bug).

 If you want to enforce the same semantics on you ES-level uses of
 descriptor objects you need to write a ES level implementation of the
 checks performed by ToPropertyDescriptor.

 I can see various ways we might improve the specified processing of
 property descriptor objects but those would generally be breaking changes
 and we would have to consider the possible impact of such changes before
 proceeding with them.

 Allen


 ___
 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: descriptors and not only own properties gotcha

2014-12-18 Thread Andy Earnshaw
*sigh* ignore me I completely misread the initial email.  Serves me right
for skim reading and speed replying during lunch.

On Thu, Dec 18, 2014 at 1:31 PM, Andy Earnshaw andyearns...@gmail.com
wrote:

 Oops, misfire.  The rest of that:

 function shadow(obj, props) {
 var ret = Object.create(obj);

 for (var k in props)
 ret[k] = props[k]

 return ret;
 }

 // Elsewhere...
 function defineSomeProps (obj) {
 var defaults = { enumerable: true, writable: true, configurable:
 true };

 Object.defineProperties(obj, {
 foo1: shadow(defaults, { value: 'bar1' })),
 foo2: shadow(defaults, { value: 'bar2' })),
 foo3: shadow(defaults, { value: 'bar3' })),
 // etc...
 });
 }

 If people have a generic shadow() function that creates an object and
 copies properties to it (less verbosely than just using Object.create),
 they could be tempted to use it to create ES3-style EWC properties.

 On Thu, Dec 18, 2014 at 1:24 PM, Andy Earnshaw andyearns...@gmail.com
 wrote:

 Can we be sure nobody's ever written something like this:

 function shadow(obj, props) {
 var ret = Object.create(obj);
 }

 On Thu, Dec 18, 2014 at 10:08 AM, Andrea Giammarchi 
 andrea.giammar...@gmail.com wrote:

 My main point is that everything you get from
 `Object.getOwnPropertyDescriptor`, beside undefined or possible abrupt
 errors, will have own properties.

 Even es5-shim/sham has been checking own properties for years [1] so I
 am pretty confident nothing will break 'cause own properties is what
 developers always expected and what they've always used despite specs.

 Again it's clear the world can live with these possibly inherited
 descriptors properties but it feels very wrong on the practical level. Too
 bad if there won't be ever a fix [2]

 [1] https://github.com/es-shims/es5-shim/issues/211#event-208821479 now
 fixed

 [2] would a new Descriptor({ownproperties:only}) instance be ever
 considered ?



 On Wed, Dec 17, 2014 at 8:37 PM, Allen Wirfs-Brock 
 al...@wirfs-brock.com wrote:


 On Dec 17, 2014, at 10:30 AM, Andrea Giammarchi wrote:

 Actually simplifying as proposal: does everyone agree that if a
 descriptor.[[Value]] is own property no further checks on inherited [[Get]]
 and [[Set]], or generally speaking Accessor Property related checks, should
 be made ?

 This would already fix the `Object.prototype.get` or `.set` case since
 I believe nobody ever used an inherited `value` property on purpose for
 descriptors ... or is it?

 It will keep `enumerable` and `writable` still potentially problematic
 but at least the following code would never fail:

 ```js
 Object.prototype.get = function () {}; Object.defineProperty(
 Object.prototype, 'toString', Object.getOwnPropertyDescriptor(
 Object.prototype, 'toString' ) );

 ```

 Thanks again for any sort of outcome (or clarification on when and if
 this will ever be fixed)


 I'm not sure what you are actually asking.  All specified internal uses
 of property descriptor objets should pas through ToPropertyDescriptor (
 http://people.mozilla.org/~jorendorff/es6-draft.html#sec-topropertydescriptor
 ) which will throw if there is any conflict between get/set and own
 value/writable properties, regardless of whether they are own or inherited.
  (If you know of any uses of such descriptor object in the ES6 spec that
 don't do this validation, please file a bug).

 If you want to enforce the same semantics on you ES-level uses of
 descriptor objects you need to write a ES level implementation of the
 checks performed by ToPropertyDescriptor.

 I can see various ways we might improve the specified processing of
 property descriptor objects but those would generally be breaking changes
 and we would have to consider the possible impact of such changes before
 proceeding with them.

 Allen


 ___
 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


Multiline template strings that don't break indentation

2014-09-09 Thread Andy Earnshaw
Hi everyone,

It's great to finally play around with template strings after noticing them
in the latest Firefox nightly.  However, I can't help but think we're
repeating mistakes of the past when it comes to multiline strings and code
tidiness.

Back when I had to write PHP code I used to feel sad that multiline strings
had to look like this:

function my_function () {
... some levels of
... indentation
$a = EOD
This is a multiline string.
It makes my code look messy because I can't indent
subsequent lines without the white space appearing
in the resulting string. :-(
EOD;

   ... more code
...
}

I've always avoided the backslash newline escape in JavaScript for the same
reason.  As happy as I am to see multiline strings appear in JavaScript in
the form of template strings, I'm not looking forward to seeing the
untidiness that goes hand in hand with it.  I'm wondering if there's a
feasible solution that could allow us to keep our code indented across
multiple lines without the formatting whitespace being included in the
resulting string.  Ideally, I'd like my multiline strings to look like this:

function myFunction () {
var a = `This is a template string.
 Even though each line is indented to keep the
 code neat and tidy, the white space used to indent
 is not in the resulting string`;

...
}

As things stand, this wouldn't look great when output in a terminal window,
a textarea or pre-formatted element in the browser.  Also, minifiers
wouldn't know if it was safe to remove this white space when minifying and
would likely leave it in.  I realise I could write a tag function that
deals with it, but that comes with additional runtime complexity and
concatenation isn't really an option since I don't think this would make
good code:

var a = tag`This is a template string.\n`
  + tag`Even though each line is indented to keep the\n`
  ...

I thought of a few potential solutions, but they come with problems of
their own.

Solution 1:  Ignore all space and tab characters following a newline until
the first non-space or tab character.  The problem with this is immediately
obvious – what if someone wanted to output a string formatted with
indentation at the start of a line?  Well, there's always `String.raw`,
which would return the string with the white space included, although I'll
admit maybe it's not ideal.

Solution 2:  Have the parser take note of the column where the delimiting `
character appears, and ignore white space on the next line only if the
length of it equals this column number + 1.  This would allow you to still
write template strings like this:

var a = `This line is not indented.
  But this line is.`

I've never written a parser, so I'm not sure how easy this would be to
implement.   I think it could potentially be confusing to people.

It could be that I'm the only person who is this fussy and it doesn't
bother anyone else, but I hope that's not the case.  I wonder if developers
won't stick to the old methods of string concatenation and avoid template
strings mostly – I've seen that happen a lot with PHP code.  At least with
here documents you could include white space as part of the delimiter and
the content was consistently aligned (even if not indented), so it wasn't
quite as bad as template strings.


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


Re: Multiline template strings that don't break indentation

2014-09-09 Thread Andy Earnshaw
Allen's is pretty clever and I'd be almost tempted to use it ;-)

On Tue, Sep 9, 2014 at 4:44 PM, Kevin Smith zenpars...@gmail.com wrote:

 You can create a really flexible dedent function/tag pretty easily:

 https://gist.github.com/zenparsing/5dffde82d9acef19e43c

 Nice, right?


I wrote a function-as-a-tag that dedented (since that's the word we're
all using) when I was playing around too.  It's *really nice*.


On Tue, Sep 9, 2014 at 5:26 PM, Alexander Kit alex@atmajs.com wrote:

I would also hope that the trailing indentions will be cut off from the
 template string. We had the case in our template engine, multiline strings
 are supported and it behaives as follows:
 - first line: contains a non-whitespace character → take the complete
 string as is and exit, otherwise:
 - secondline - lastline → get the smallest indention
 - secondline - lastline → trim the indention
 - last line: contains only whitespaces → remove the line

 This should cover all the cases, or do somebody has other ideas?


Git and linting tools usually bark at you if you have trailing white space
anyway, if you don't have your editor automatically removing it.  That
aside, are you suggesting that a template string like this:

var a = `
This has
no indentation
`;

should have the indentation removed, but not in the case where a non-white
space character is between the first ` and the newline?  Wouldn't that be a
tad confusing?  Also, it's common in console applications to have a
trailing newline (although you could just concat one of course).  Taking
the smallest amount of indentation away from each line is interesting,
though, and probably less confusing than my suggestion of removing white
space up to the column of the first `.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Chained comparisons from Python and CoffeeScript

2013-07-24 Thread Andy Earnshaw
On Tue, Jul 23, 2013 at 7:52 PM, Brendan Eich bren...@mozilla.com wrote:

 Andy Earnshaw wrote:

  On Mon, Jul 22, 2013 at 9:08 PM, Brendan Eich bren...@mozilla.commailto:
 bren...@mozilla.com wrote:

  Opt-in sounds like a better solution, if pragmas are to be
 entered into the specification then it could even become part of

 use strict;


 Your point applies here too, though. use strict; (did you forget
 the quotes) has meaning in ES5, no meaning before, and therefore
 not likely new meaning after ES5.


 I didn't forget the quotes :-) I remembered reading the proposal at
 harmony:pragmas, but I didn't check the harmony:proposals page to see what
 its fate had been.  I was thinking that an ES6 use strict wouldn't need to
 retain compatibility with ES5 because of the differing syntax.  Even still,
 you raise a good point, changing the meaning for ES6 might have been
 confusing.


 Did you mean to reply-all? Just checking.


Oops.  Still not used to replying to mailing lists.  I did this a couple of
times on other threads and didn't realise why everyone was saying almost
the exact same things I said as if I'd not said them!


  We do not plan to evolve use strict. Nor do we plan to remove
 the quotes (we've considered that at
 
 http://wiki.ecmascript.org/**doku.php?id=harmony:pragmashttp://wiki.ecmascript.org/doku.php?id=harmony:pragmas,
 deferred
 from 
 http://wiki.ecmascript.org/**doku.php?id=harmony:proposalshttp://wiki.ecmascript.org/doku.php?id=harmony:proposals--
 note strikethrough). It's possible more pseudo-pragmas in quotes
 may be standardized but as noted: wicked fight, requiring lots of
 data and careful argumentation.


 I would really like to see this; the one-time evaluation of each operand
 could eliminate the need for temporary variables and the shorter, more
 readable code just sweetens the deal.  However, I think if we're going to
 introduce more pseudo-pragmas, they should probably provide a significant
 change like Claude indicated, fixing typeof null and several other
 improvements (although I'm not sure I agree with all his ideas for a
 perfect language ;-)).


 I think he was making the point that perfect is not an option (I am
 able to make coffee from within my preferred browser).
 We almost certainly are not going to fork the language with a pragma, but
 if we do it will be new syntax, to choke old browsers. Otherwise the
 testing burden doubles (again; this happened with use strict; in ES5 due
 to its runtime semantic changes).


Yeah, I suppose it's not such a good idea forking the language at all.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Chained comparisons from Python and CoffeeScript

2013-07-22 Thread Andy Earnshaw
On Mon, Jul 22, 2013 at 5:25 AM, Brendan Eich bren...@mozilla.com wrote:


 This is the part we can't determine. The web is not just the
 Google-indexable (by what user agent?) part, but paywalled and intranet
 content as well. I've written before that finding true positives helps
 reject a proposed incompatible change, but finding no positives does not
 prove that we can make the change.

 Furthermore, the first browser to roll the dice and face breakage loses,
 making implementors generally unwilling to take even likely-small risks.
 This browser Prisoner's Dilemma can be helped by cooperation, e.g., among
 TC39ers, but even then only for a big enough payoff. See the typeof null ==
 null attempt early in ES6 development for an example.


typeof null == null is a different case though.  typeof is a requirement
for checking the existence of pre-declared variables, so you could expect
something like, if (typeof someVar === object  someVar === null), to
appear at least in a few places on the web.  Tab's saying that this
proposal wouldn't break much (if anything) because code isn't written like
this anywhere: it wouldn't be readable or reliable.  Writing a  b  c in
ES=5 would be either stupidity or ignorance (in the case of the latter
then this proposal would probably fix more code than it breaks).  For
equality, there might be a problem where code is written like, if (a === b
=== true), where a and b are something other than booleans.  I could maybe
see an outside chance that this appears somewhere on the web or an
intranet, but maybe there's a way we can deal with it so it doesn't break
backwards compatibility.

use chained comparisons;, anyone? ;-)
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Chained comparisons from Python and CoffeeScript

2013-07-19 Thread Andy Earnshaw
On 19 Jul 2013 20:21, Tab Atkins Jr. jackalm...@gmail.com wrote:

 Well, that's a bad example, because it's true with chained operators
 too.  Let c = 1.5, though, and you get different behavior.

 This type of code is broken in the first place, though.  Are we
 assuming that it's prevalent enough to cause problems?


Well, I was hoping it wouldn't. I can't imagine anyone writing this kind of
code unless they expect it to work in the same way as Python (and by chance
it did when they tested).
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Unicode aliases for ASCII operators

2013-07-18 Thread Andy Earnshaw
I was thinking about this subject a while ago and found an interesting
thread [1] on the Scala debate mailing list.  I was going to raise this
question back then, but I forgot about it until now.  If I understand
correctly, several Unicode symbols are aliases for ASCII operators, for
example:

=  ⇒   // implemented
-  ←   // implemented
-  →   // implemented


At the time I saw this, I thought it was pretty interesting.  The thread
goes on to suggest more could be implemented:

=  ≥
=  ≤

*   ×   multiplication  // this one's probably an ASCII approximation
/   ÷   division
!   ¬   logical negation
^   ⊕   exclusive or
!=  ≠   not equal

Perhaps we could think about this for ECMAScript, along with the rest(e.g.
≈ for == and ≡ for ===).  Would there be any harm in it if we kept the
ASCII equivalents intact?  By putting them in we may be looking toward the
future where this kind of thing is (hopefully) more common in programming
languages (and on keyboards).

Andy

 [1] http://www.scala-lang.org/node/4723
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Chained comparisons from Python and CoffeeScript

2013-07-18 Thread Andy Earnshaw
I apologise if I'm making more suggestions that have been discussed in the
past, I'm genuinely searching before I click the compose button and not
finding anything!

I'd like to see this implemented, at least for greater/less than (-or equal
to).

a  b  c
a = b = c

Desugars to

a  b  b  c
a = b  b = c

For a real-world example

var pos = element.getBoundingClientRect(),
 inView = 0 = pos.left  pos.left = window.innerWidth  0 =
pos.top  pos.top = window.innerHeight;

Could be rewritten as

var pos = element.getBoundingClientRect(),
 inView = 0 = pos.left = window.innerWidth  0 = pos.top =
window.innerHeight;

There's a lot to be said for readability, and each operand needs only be
evaluated once, so it could help avoid the need for creating variables to
store the result of a function or a getter (or prevent the need for either
to be invoked more than once).

It's also supported (as the title suggests) by Python [1], Perl 6 [2] and
CoffeeScript [3].  Those languages support chaining the equality operators
too.

It's potentially a breaking change, because

0  1  1

evaluates to false in current implementations because

(0  1)  1

However, I think we'd be hard pressed to find code like this with
greater/less than or equality operators.

[1] http://docs.python.org/2/reference/expressions.html#not-in
[2] http://en.wikipedia.org/wiki/Perl_6#Chained_comparisons
[3] http://coffeescript.org/#comparisons
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Language Negotiation API

2013-07-15 Thread Andy Earnshaw
Would you expect to support the same locales as Intl constructors in your
library?  Can you safely make that assumption?

Canonicalisation makes sense because I would expect a library to
canonicalise the tag and then try and load the file containing relevant
data whether the native API supports it or not. Forgive me if I'm
misunderstanding something, I didn't have a look at your project in great
detail.

Andy
On 15 Jul 2013 16:49, Zbigniew Braniecki zbranie...@mozilla.com wrote:

  As for LookupAvailableLocales, there might be a problem with Zbigniew's
  vision of it as any tags would be returned without extensions. I'm not
 sure
  if this is something that we'd need to worry about, though.

 No, that's good, because locales will be stored under names without them
 as well.

 Cheers,
 zb.

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


Re: Language Negotiation API

2013-07-15 Thread Andy Earnshaw
On Mon, Jul 15, 2013 at 9:37 PM, Anne van Kesteren ann...@annevk.nl wrote:

 On Sun, Jul 14, 2013 at 5:20 AM, Andy Earnshaw andyearns...@gmail.com
 wrote:
  I certainly do, at least for Canonicalize-.  I've come across one user
 agent
  that returns `navigator.language` in non-canonical form which presented a
  small problem for data I had stored with canonical file names.  This was
 a
  WebKit based Smart TV platform from 2012, so it was fairly recent, there
  could be other platforms or frameworks that do the same.

 FWIW, exposing a new API because another API is broken in a particular
 implementation is a known anti-pattern. We should fix problems at the
 source.


Normally, I would agree.  However, I was just using my scenario as an
example for where exposing the API would have been useful for me.  I can
also think of a few other reasons:

 - Language tags can be in extlang form or canonical form.  Depending on
the source providing the language tag, it's not guaranteed to be the
canonical form (extlang form can reinstate extlang subtags that were
removed during canonicalisation).
 - The Internationalization API doesn't cover all aspects of its namesake,
like translation, or formatting of postal codes or telephone numbers, as a
few examples.  Developer libraries could augment Intl with this data, so it
would make lives easier if we exposed CanonicalizeLanguageTag to be used by
such libraries.
 - Canonicalisation has at least a couple of optional steps (like
normalising case or ordering variant subtags) so exposing a canonicalizing
method would give developers a way to achieve consistency with the
Internationalisation API.

navigator.language isn't part of any stable specification, and even the
current HTML 5.1 draft doesn't specify that tags should be returned in
canonical form.  Do you think it would be a good idea to raise an issue for
this?

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


Re: Language Negotiation API

2013-07-14 Thread Andy Earnshaw
On Sun, Jul 14, 2013 at 2:07 AM, Norbert Lindenberg 
ecmascr...@lindenbergsoftware.com wrote:

  CanonicalizeLanguageTag isn't even defined for non-structurally valid
 language tags. That's why I meant a combined IsStructurallyValidLanguageTag
 + CanonicalizeLanguageTag function is more useful than access to the bare
 CanonicalizeLanguageTag function.

 Correct. As currently specified, the CanonicalizeLanguageTag abstract
 operation assumes that its input is a String valueI'm not too sure about
 the that's a structurally valid language tag. An API cannot make such
 assumptions - it has to be ready to deal with any input, as well as the
 absence of input. It has to do something like the steps in
 CanonicalizeLocaleList 8.c.ii-iv before calling the current
 CanonicalizeLanguageTag.


You're both right, it assumes a string and doesn't check validity.  That
didn't occur to me, it's been a few months since my implementation.


 Before we get too much into spec details: Do others believe that exposing
 API as proposed by Zbigniew would be useful?


I certainly do, at least for Canonicalize-.  I've come across one user
agent that returns `navigator.language` in non-canonical form which
presented a small problem for data I had stored with canonical file names.
 This was a WebKit based Smart TV platform from 2012, so it was fairly
recent, there could be other platforms or frameworks that do the same.

As for LookupAvailableLocales, there might be a problem with Zbigniew's
vision of it as any tags would be returned without extensions.  I'm not
sure if this is something that we'd need to worry about, though.

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


Re: Language Negotiation API

2013-07-13 Thread Andy Earnshaw
Sorry g, forgot the Cc :-)

On Thu, Jul 11, 2013 at 11:52 PM, Zbigniew Braniecki zbranie...@mozilla.com
 wrote:

 ...



1) CanonicalizeLanguageTag [1]

 Because language tags come from developers and users, ability to
 canonicalize them is crucial to us. ECMA 402 specifies this function and
 all we need is to expose it in the API


I was thinking the same thing recently, at least for
CanonicalizeLanguageTag. I was working with a platform that gave me a
language tag in non-canonical form, meaning I had to either canonicalize it
or rename my language files to match the same non-canonical form.  Exposing
it as `Intl.canonicalizeLanguageTag(tag)` seems like a good idea.



 1.1) CanonicalizeLocaleList [2]

 That would also be nice to have :)


I don't think you could expose CanonicalizeLocaleList directly without
altering it to return an array, you'd have to do something similar to step
5 of LookupSupportedLocales.  I'm not sure we could change that function in
the spec without other abstracts potentially being affected by tainted a
Array.prototype, so I guess you'd need to specify a new function.  In which
case I'm wondering if maybe you'd be better off with
`Intl.canonicalizeTags(tags)` which would cover both
CanonicalizeLanguageTag() and CanonicalizeLocaleList().

2) LookupAvailableLocales

 This function has almost identical heuristic to LookupSupportedLocales [3]
 with a single difference being in step d).

 Replace:
  - If *availableLocale* is not *undefined*, then append *locale* to the
 end of *subset*. 
 with:
  - If *availableLocale* is not *undefined*, then append *availableLocale*to 
 the end of
 *subset*. 

 The reason behind this is that localization frameworks need to choose the
 available locales that closest match the user preferences. If we used
 LookupSupportedLocales, we will receive the locales that user requested,
 not ones that are available on the system.
 In result on each of those, we'd have to call BestAvailableLocale [4] to
 receive the tag name that we can pull resources for.


You can at least work around this for a single locale with
Intl.NumberFormat(tag).resolvedOptions().locale.  If you're already using
the native localisation APIs, this might not be too much of a hindrance.
 What you're suggesting would need to be a function property of the
constructors, e.g. `Intl.NumberFormat.availableLocalesOf()`.  I'm not so
sure this approach makes sense, though; wouldn't you still have a problem
if your own API provided variant data where the system does not?



 With that one change, we are actually going to receive the right set of
 language tags that we can then use to provide best language with fallbacks.

 Example implementation of this is L20n localization framework [5] which
 copies Mozilla ECMA 402 code to expose the required functions and uses
 custom function called prioritizeLocales to build the final locale fallback
 chain.

 Comments? Feedback? Next steps? :)

 Cheers,
 g.
 --

 Mozilla (http://www.mozilla.org)

 [1] http://ecma-international.org/ecma-402/1.0/index.html#sec-6.2.3
 [2] http://ecma-international.org/ecma-402/1.0/index.html#sec-9.2.1
 [3] http://ecma-international.org/ecma-402/1.0/index.html#sec-9.2.6
 [4] http://ecma-international.org/ecma-402/1.0/index.html#sec-9.2.2
 [5] https://github.com/l20n/l20n.js/blob/master/lib/l20n/intl.js#L431

 ___
 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: Language Negotiation API

2013-07-13 Thread Andy Earnshaw
On Sat, Jul 13, 2013 at 1:05 PM, André Bargull andre.barg...@udo.eduwrote:

  ...
 Only exposing CanonicalizeLanguageTag does not seem useful to me without
 having access to IsStructurallyValidLanguageTag. Most likely a combined
 IsStructurallyValidLanguageTag + CanonicalizeLanguageTag function is
 necessary/wanted for most use cases.


Hmm.  I'm not sure I'd agree it's necessary.
 IsStructurallyValidLanguageTag makes sense as an abstract function because
you need to throw accordingly when an invalid tag is passed to the
constructors or methods.  However, it's still the developer's
responsibility to make sure their tags are valid during the development
process.  Canonicalisation would still throw an error if the tag is invalid.


  I don't see why you'd need to change CanonicalizeLocaleList at all. Just
 let it return the internal list as-is, and then define
 `Intl.canonicalizeLocaleList` like so:


Lists are internal, they aren't part of the ECMAScript language.  It makes
no sense to return an internal list to ECMAScript code unless you intend to
go the whole hog and specify them with a constructor/prototype.


 It also needs to be considered whether the duplicate removal in
 CanonicalizeLocaleList creates any issues for users of a potential
 `Intl.canonicalizeLocaleList` or `Intl.canonicalizeTags` function.


Perhaps.  Are there any cases you think of where removing duplicates would
be a problem?

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


Freezing object properties or array values, whilst keeping them extensible

2013-06-04 Thread Andy Earnshaw
Something that occurred to me today is that we have methods for locking
down objects in different ways except for preventing changes to existing
properties.  We have:

 - Object.seal to prevent new properties being added or existing properties
being deleted
 - Object.preventExtensions to prevent new properties being added
 - Object.freeze to prevent new properties being added or existing
properties being altered/deleted

Let's say, though, that my library has a function that accepts an object as
an argument, performs some changes to the values of properties on that
object and returns it to the developer's code for use in a different
function provided by my library.  If I didn't want the developer changing
any of the properties the function sets, I'd have to copy all properties
across to a new object.  That's all well and good, but what if it's an
array?  The length property of an array isn't configurable, so you can't
prevent it being written without freezing it which, in turn, prevents
extensions altogether.

Array.create might have taken care of that, depending on how it was
implemented, but it seems as though that's been deferred in favour of the
| operator proposal.

If it's not too late for ES6 proposals, I'd like to suggest that we add
either an function to freeze only existing properties of an object, e.g.
Object.lock(), or a function to freeze arrays, e.g. Array.freeze().  The
latter would only freeze the length property and existing array index
properties, keeping it extensible.

Other than introducing another aspect of control over the library user, I
could see this being useful as an optimisation; if the array elements are
locked and you can confirm it was locked by your code then you could make
assumptions about the last element in the array based on an inspection of
the first, eliminating the need for a loop.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: for own(...) loop (spin-off from Re: for..in, hasOwnProperty(), and inheritance)

2011-11-09 Thread Andy Earnshaw
Should ES.next provide sugar for the recommended pattern? To make it compose
with declarations and destructuring in the for head, it should use a
contextual keyword immediately after 'for':

 

  for own (i in o) {

body

  }

 

This is a small thing but it might pay off in the long run.

 

I was thinking of raising a similar suggestion, but I wasn't sure when to
jump in and bring it up.  However, I think it could be more useful to
introduce another operator like `in` as syntactic sugar for `hasOwnProperty`
and have it work in a `for` loop similar to how `for...in` works too.

 

  /* Desugared property check - */ o.hasOwnProperty(prop)

  /* Sweetened property check - */ prop on o

 

  /* Desugared loop - */ for (i in o) { if o.hasOwnProperty(i) { ... }

  /* Sweetened loop - */ for (i on o) { ... }

 

I could see it being useful as an operator in situations where you might
have an object map:

 

  var obj = { key1: val1, key2: val2 }

 

  if (key1 on obj) {  

 // ...

  }

 

I think Dr Rauschmayer mentioned Python's `on` and I think it fits in here
quite nicely.  `in` for anywhere in the chain, `on` for direct properties.
If it's a little too close for comfort, you could stick with `own` or
reverse the operands and call it `hasown`.  Perhaps that would seem too
inconsistent, though.  Overall, I think it's a great idea.  It's fairly
common for developers to forget to do a `hasOwnProperty` check when
enumerating.  As for `Object.keys(o).forEach()`, the speed just doesn't
compare and it doesn't look too great.

 

Andy Earnshaw

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