Default values for nulls

2020-10-13 Thread Michael Luder-Rosefield
I know I am not the only one who has had several perfectly good use-cases
for default values disallowed, because the value coming in was `null`, not
`undefined`.

I cannot be the only one who has let bugs slip in because of failing to
consider this case.

So, if we can find a non-confusing and simple way to alter the spec to
allow for handling this, I imagine it would be considered useful and wanted.

The obvious candidate is the nullish coalescing operator, which is already
part of the spec. Unfortunately, it is currently invalid to indicate
default values with it. I can't see any reason against changing this.

```
function foo1 (x = 4) {
  console.log(x);
}

// currently causes SyntaxError
function foo2 (x ?? 4) {
  console.log(x);
}

foo1(null); // null
foo1(undefined) // 4

foo2(null); // 4
foo2(undefined) // 4

// currently causes SyntaxError
// should give x === null, y === 4
const { x = 2, y ?? 4 } = { x: null, y: null };
```
--
Dammit babies, you've got to be kind.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Property Accessor Function Shorthand

2019-12-03 Thread Michael Luder-Rosefield
At the cost of adding more code, but giving more power, perhaps what we
want is something akin to Kotlin's `it` keyword:
https://kotlinlang.org/docs/reference/lambdas.html?_ga=2.238822404.500195435.1575368476-1345353619.1575368476#it-implicit-name-of-a-single-parameter

*it: implicit name of a single parameter*
*It's very common that a lambda expression has only one parameter.*
*If the compiler can figure the signature out itself, it is allowed not to
declare the only parameter and omit ->. The parameter will be implicitly
declared under the name it:*
ints.filter { it > 0 } // this literal is of type '(it: Int) -> Boolean'


What we'd want is something concise and non-ambiguous to fulfill the same
role; something that cannot currently be a valid identifier, maybe. This is
the point where I start scanning the keyboard for underutilised symbols...
I'm thinking the hash symbol would work. To re-use the original example:

```js
const activeProducts = products.filter(#.active);
const productNames = products.map(#.name);
const sortedProducts = _.sortBy(products, #.name);
const { true: activeProducts, false: inactiveProducts } =
_.groupBy(products, #.active);
```

It makes intuitive sense in 2 ways, I think; # makes you think of the
object hash you're extracting a property from, and also is familiar as
something's id from CSS selectors.

We could also extend it to represent multiple parameters: # is also aliased
as #0, the 2nd parameter is #1, etc.

Further, dynamic properties would work too: `const fooProducts =
products.filter(#[foo]);
*-*-
Dammit babies, you've got to be kind.


On Mon, 2 Dec 2019 at 22:32, Waldemar Horwat  wrote:

> On 11/24/19 9:17 PM, Bob Myers wrote:
> > FWIW, the syntax `.propName` does appear to be syntactically unambiguous.
>
> It conflicts with contextual keywords such as `new . target`.
>
>  Waldemar
> ___
> 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: Ternary operator enhancement proposal

2019-11-13 Thread Michael Luder-Rosefield
I put forward a similar proposal a while back:
https://esdiscuss.org/topic/proposal-result-forwarding-ternary-operator
--
Dammit babies, you've got to be kind.


On Wed, 13 Nov 2019 at 02:46, Jacob Pratt  wrote:

> Aside from the fact that using a non-reserved identifier would break
> back-compatibility, I'm fairly certain pattern matching would allow for not
> recalculating the value while also being far more readable.
>
> On Tue, Nov 12, 2019, 21:43 devlato  wrote:
>
>> Hey folks,
>>
>> not sure if you haven't discussed something similar, but what do you
>> think about making an enhancement for the ternary operator, to make it more
>> powerful?
>> I've created a small explanatory doc on GitHub:
>> https://github.com/devlato/proposal-ternary-placeholder
>>
>> Warmest regards,
>> Denis
>>
>> ___
>> 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: Modify Promise.all() to accept an Object as a parameter

2019-10-14 Thread Michael Luder-Rosefield
The RSVP library uses Promise.hash, which seems sensible enough that I'm
surprised no-one has mentioned or suggested it here.
--
Dammit babies, you've got to be kind.


On Mon, 14 Oct 2019 at 09:17, Michał Wadas  wrote:

> Established name is Promise.properties
>
> On Mon, 14 Oct 2019, 09:29 Cyril Auburtin, 
> wrote:
>
>> maybe a naming like: `Promise.allObject`
>>
>> ```js
>> Promise.allObject = obj => {
>>   if (obj && !obj[Symbol.iterator]) {
>> return Promise.all(
>>   Object.entries(obj).map(async ([k, v]) => [k, await v])
>> )
>>   .then(Object.fromEntries);
>>   }
>>   return Promise.all(obj);
>> }
>>
>> var delay = t => new Promise(r => setTimeout(r, t));
>> console.time(1); console.log(await Promise.allObject({foo:
>> delay(110).then(()=>1), bar: delay(120).then(()=>2)})); console.timeEnd(1)
>> ```
>>
>> On Sun, Oct 13, 2019 at 8:55 PM Isiah Meadows 
>> wrote:
>>
>>> Maybe Promise.join(object)? Also, if a map is passed (or any iterable),
>>> it should be joined into a map.
>>>
>>> At the most basic level:
>>>
>>> ```js
>>> Promise.join = (o) => {
>>> let isMap = o[Symbol.iterator] != null
>>> let ps = (
>>> isMap ? Array.from : Object.entries
>>> )(o)
>>> let ks = ps.map(p => p[0])
>>> return Promise.all(ps.map(p => p[1]))
>>> .then(vs => {
>>> let ps = vs.map((v, i) => [ks[i], v])
>>> return isMap
>>> ? new Map(ps)
>>> : Object.fromEntries(ps)
>>> })
>>> }
>>> ```
>>>
>>> On Sun, Oct 13, 2019 at 13:40 Cyril Auburtin 
>>> wrote:
>>>
 OP probably means he would like Promise.all to return an object as
 well, if an object if given

 It's possible to hack an object to be iterable, but Promise.all
 already return an array unfortunately

 On Sun, Oct 13, 2019 at 7:16 PM Boris Zbarsky  wrote:

> On 10/12/19 12:52 AM, Jacob Bloom wrote:
> > const responses = await Promise.all(requests);
>
> As opposed to:
>
>const responses = await Primise.all(requests.values());
>
> which works right now?
>
> -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

>>> --
>>> -
>>>
>>> Isiah Meadows
>>> cont...@isiahmeadows.com
>>> www.isiahmeadows.com
>>>
>> ___
>> es-discuss mailing list
>> es-discuss@mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Use hashes as keys instead of toString() for values like object, function to index objects

2019-09-09 Thread Michael Luder-Rosefield
Why not both?

My point is that Map/WeakMap do a lot of what people historically use
Object for, but in a better way; certainly, they solve Tadas's issue here.

The trouble is that Objects have a lot of convenient sugar around them that
make them easier, and more pleasant, to use. We really shouldn't be in a
position where people choose the worse option simply out of sugar.

--
Dammit babies, you've got to be kind.


On Mon, 9 Sep 2019 at 02:26, J Decker  wrote:

>
>
> On Sun, Sep 8, 2019 at 1:24 PM Michael Luder-Rosefield <
> rosyatran...@gmail.com> wrote:
>
>> I'd suggest that the best way of doing this, without breaking existing
>> code, is to put some sugar around Maps so that they can be used in a more
>> Object-y way. For starters, Map literal declarations and assignment could
>> benefit from this.
>>
>> or Just use a WeakMap
>
>
>> Suggestions for syntax welcome!
>>
>> On Sun, 8 Sep 2019, 12:36 Tadas Lapė,  wrote:
>>
>>> The problem
>>>
>>> Javascript allows to index objects not only with strings, numbers, but
>>> also with objects. It uses toString() object method to calculate the object
>>> index. If method is not overwritten, the generated index is "[object
>>> Object]". Many users do not know this or forget this and cause different
>>> objects going into same index when using more of them.
>>>
>>> The solution
>>>
>>> Instead of using the default value "[object Object]" for objects, use
>>> their hash codes. You can also prepend them with "function:" or "object:"
>>> to let the user know index origin when iterating over object keys. And if
>>> person has overwritten the behavior of toString() object method, use it's
>>> returned value as index (to consider). This should be less error-prone.
>>> ___
>>> 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: Use hashes as keys instead of toString() for values like object, function to index objects

2019-09-08 Thread Michael Luder-Rosefield
I'd suggest that the best way of doing this, without breaking existing
code, is to put some sugar around Maps so that they can be used in a more
Object-y way. For starters, Map literal declarations and assignment could
benefit from this.

Suggestions for syntax welcome!

On Sun, 8 Sep 2019, 12:36 Tadas Lapė,  wrote:

> The problem
>
> Javascript allows to index objects not only with strings, numbers, but
> also with objects. It uses toString() object method to calculate the object
> index. If method is not overwritten, the generated index is "[object
> Object]". Many users do not know this or forget this and cause different
> objects going into same index when using more of them.
>
> The solution
>
> Instead of using the default value "[object Object]" for objects, use
> their hash codes. You can also prepend them with "function:" or "object:"
> to let the user know index origin when iterating over object keys. And if
> person has overwritten the behavior of toString() object method, use it's
> returned value as index (to consider). This should be less error-prone.
> ___
> 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: Optional chaining syntax but with the "mice" operator ?

2019-09-07 Thread Michael Luder-Rosefield
This is getting very reminiscent of my 'forwarding ternary' operator (or
whatever I called it) I suggested a couple of years ago. I believe you were
involved in the discussion, Andrea...!

```
const val = foo() ?!
  (x) => x.bar.baz :
  someFallbackValue;
```

On Sat, 7 Sep 2019, 10:17 Andrea Giammarchi, 
wrote:

> To better answer, let's start dropping any direct access and put a payload
> in the mix.
>
> As example, in the `foo()?.bar.baz` case, you might end up having `null`
> or `undefined`, as result, because `foo().bar` existed, but `bar.baz`
> didn't.
>
> In the `foo()?.bar?.baz` case, you might end up having `foo().bar`,
> because `bar.baz` didn't exist.
>
> But what if you are not interested in the whole chain, but only in a main
> specific point in such chain? In that case you would have `foo()?.bar.baz
> ?? foo()`, but you wouldn't know how to obtain that via `foo()?.bar?.baz ??
> foo()`, because the latest one might result into `foo().bar`.
>
> Moreover, in both cases you'll end up multiplying the payload at least *
> 2, while the mouse trap will work like this:
>
> ```js
> foo() ```
>
> if either `foo().bar` or `bar.baz` don't exist, the returned result is
> `foo()`, and it's computed once. You don't care about `foo().bar` if
> `bar.baz` is not there, 'cause you want to retrieve `foo()` whenever you
> have a failure down the chain.
>
> Specially with DB operations, this is a very common case (abstraction
> layers all have somehow different nested objects with various info) and the
> specific info you want to know is usually attached at the top level bject,
> while crawling its sub properties either leads to the expected result or
> you're left clueless about the result, 'cause all info got lost in the
> chain.
>
> The `foo() `foo().bar` existed, there's no way to expect `foo()` as result, and if
> it's `bar` that you're after you can write instead `foo()?.bar that if `baz` is not there, `bar` it is.
>
> This short-circuit the need for `??` in most cases, 'cause you already
> point at the desired result in the chain in case the result would be `null`
> or `undefined`.
>
> However, `??` itself doesn't provide any ability to reach any point in the
> previous chain that failed, so that once again, you find yourself crawling
> such chain as fallback, resulting potentially in multiple chains and
> repeated payloads.
>
> ```js
> // nested chains
> foo()?.bar.baz?.biz ?? foo()?.bar.baz ?? foo()?.bar;
>
> // mouse trap
> foo()?.bar ```
>
> Above example would prefer `foo().bar` if it exists, and if either
> `bar.baz` or `bar.baz.biz` returned `null` or `undefined`.
>
> I hope this clarifies further the intent, or the simplification, that such
> operator offers: it's a complementary hint for any optional chain, it
> doesn't have to be used, but when it does, it's visually semantic in its
> intent (at least to my eyes).
>
> Regards
>
>
>
>
> On Fri, Sep 6, 2019 at 11:20 PM Tab Atkins Jr. 
> wrote:
>
>> On Fri, Sep 6, 2019 at 8:04 AM Andrea Giammarchi
>>  wrote:
>> > Indeed I'm not super convinced myself about the "branching issue"
>> 'cause `const result = this?.is?.branching?.already` and all I am proposing
>> is to hint the syntax where to stop in case something else fails down the
>> line, as in `const result = this.?.is> other part is not reached, there is a certain point to keep going (which
>> is, example, checking that `result !== this`)
>>
>> Important distinction there is that ?. only "branches" between the
>> intended type and undefined, not between two arbitrary types. The
>> cognitive load between those two is significantly different.
>>
>> In particular, you can't *do* anything with undefined, so
>> `foo?.bar.baz` has pretty unambiguous semantics - you don't think you
>> might be accessing the .baz property of undefined, because that
>> clearly doesn't exist.
>>
>> That's not the case with mouse, where it's not clear, at least to me,
>> whether `foo> `foo.bar.baz ? foo.bar.baz : foo` or even `foo.bar ? foo.bar.baz :
>> foo`. All three seem at least somewhat reasonable, and definitely
>> *believable* as an interpretation!
>>
>> ~TJ
>>
> ___
> 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: Optional chaining syntax but with the "mice" operator ?

2019-09-05 Thread Michael Luder-Rosefield
Another pattern it could be useful in is with, say, nosql dbs where
something might be an object or id reference:

```
const fooId = foo
wrote:

> Another use case that I believe will be common is the following one:
>
> ```js
> // current state of the art
> const result = dbQuery(data)?.rows ?? 'did it just failed or what?';
>
> // VS the "mice operator"
> const result = dbQuery(data)
> // if it was rows
> if (Array.isArray(result))
>   console.log(result);
> else if (result instanceof Error)
>   console.error(result.message);
> else
>   console.warn(`unexpected result: ${result}`);
> ```
>
> Ideally, the "mice" should grant chaining up to its latest presence, but I
> wouldn't know right now how to reference to it ...
>
> ```js
> // if no ?? is needed, this might work
> const result = dbQuery(data)
> // if ?? is needed, no idea how to back-reference the latest successfull
> "mice" result
> ```
>
>
>
>
> On Thu, Sep 5, 2019 at 11:44 PM Tab Atkins Jr. 
> wrote:
>
>> On Thu, Sep 5, 2019 at 2:39 PM Andrea Giammarchi
>>  wrote:
>> >
>> > This is basically a solution to a common problem we have these days,
>> where modules published in the wild might have a `default` property, to
>> support ESM logic, or not.
>> >
>> > ```js
>> > // current optional chaining logic
>> > const imported = exported?.default ?? exported;
>> >
>> > // my "mice operator" proposal
>> > const imported = exported> > ```
>> >
>> > Semantically speaking, not only `> also points at its previous value in case the chaining didn't work.
>> >
>> > Beside the basic example, the "mice operator" might save CPU cycles
>> when it comes to involving more complex expressions, i.e.
>> >
>> > ```js
>> > // current "solution"
>> > const thing = require('thing')?.default ?? require('thing');
>> >
>> > // mice operator
>> > const thing = require('thing')> > ```
>> >
>> > This is also easily tranpilable, so kinda a no-brainer for modern dev
>> tools to bring in.
>> >
>> > TL;DR specially for cases where an accessed property should fallback to
>> its source, this operator might save both typing and CPU time whenever it's
>> needed.
>>
>> I find it a rather curious pattern, that I'd never seen before! Is it
>> used in anything besides this ESM-compat thing you're talking about?
>>
>> (Saving CPU cycles is not a convincing argument; it's trivial to write
>> such a line over two declarations and avoid any expensive
>> recomputations.)
>>
>> ~TJ
>>
> ___
> 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: Moving forward with function decorators

2019-09-04 Thread Michael Luder-Rosefield
I don't see any mention of class/object shorthand methods; would these be
trivial, do you think?

```
class FooClass {
  @dec1 @dec2
  bar () { }
}

const fooObj = {
 @dec1 @dec2
  bar () { }
}
```
--
Dammit babies, you've got to be kind.


On Wed, 4 Sep 2019 at 11:49, Андрей Губанов 
wrote:

> Here I described my thoughts about this topic
> https://github.com/finom/function-decorators-proposal. The main idea of
> moving forward with function decorators is to make them behave like there
> were defined and wrapped by another function, not more, and get rid of any
> hoisting when they're used.
>
> Function expression and arrow functions
>
> const foo = @decorator1 @decorator2 function bar() { return "Hello" }
> // Will become:
> const foo = decorate([decorator1, decorator2], function bar() { return 
> "Hello" });
>
> And
>
> const foo = @decorator1 @decorator2 () => "Hello"
> // Will become:
> const foo = decorate([decorator1, decorator2], () => "Hello");
>
>
> Function
> declarations
>
> And this is the most important. I propose to make a decorated function
> declaration behave as let definition.
>
> @decorator1 @decorator2 function foo() { return "Hello" }
> // Will become:
> let foo = decorate([decorator1, decorator2], function foo() { return "Hello" 
> }); // no hoisting!
>
> ___
> 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] Optional chaining

2019-08-23 Thread Michael Luder-Rosefield
Another similar thing I've used is with String interpolation; if you use a
similar pattern, e.g.,

``` `$[items.length} item${items.length !== 1 ? 's' : ''} in collection` ```

When you want to conditionally add either some text, or nothing at all, you
are forced to use the ternary with an empty string, or some workaround. In
terms of a proposal, the first thing I think we need to know is: can the
interpreter detect that it's in a template literal, in the same manner as
it detects ?...  being in an object/array declaration context?
--
Dammit babies, you've got to be kind.


On Fri, 23 Aug 2019 at 02:01, Beknar Askarov 
wrote:

> Problem
>
> Spreading is great! It contributes towards "declerativity" of the language
> and reduces verbosity. I see one more feature to add to improve it.
>
> Consider following
>
> [
>   1,
>   condition && 2,
>   condition && 3,
>   4,
> ].filter(Boolean) // filtering needed to remove falsy values
> // Results in
> [1, 2, 3, 4] // if condition is `truthy`// and
> [1, 4] // if not truthy.
>
> Another way to achieve the same result without the need of filtering after
>
> [
>   1,
>...(condition ? [2, 3] : []), // note extra [] in the end, to avoid errors
>   4,
> ]
>
> Similar pattern with objects
>
> {
>   ...(condition ? { foo: 'bar' } : {}), // extra {}
> }
>
> Another pattern is when condition is the object itself, when it is known
> that type is one or falsy
>
> [
>   item1,
>   item2,
>   ...(itemsOrNull || []) // extra []
> ]
>
> Similar for objects
>
> {
>   ...(obj || {}), // extra {}
> }
>
> I see these patterns appearing very often. And these are cleanest examples
> I have seen so far.
> ProposalOptional spreadingWith condition
>
> // Arrays
> [
>   1,
>   ?...(condition && [2, 3]), // no extras:)
>   3,
> ]// Objects
> {
>   ?...(condition && { foo: 'bar' }) // no extras:)
> }
>
> When condition is the object
>
> [
>   item1,
>   item2,
>   ?...itemsOrNull // no extras at all:) even (...)
> ]
>
> These look nicer and can be good for performance since (?...), since no
> cleanup is needed after to remove falsy values or extra spreading even when
> it is not needed.
>
> Looks intuitive (since: https://github.com/tc39/proposal-optional-chaining
> )
> Plays nice with typeings.
>
> What do you think? https://es.discourse.group/t/optional-spreading/93
> ___
> 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: Modulo Operator %%

2019-08-15 Thread Michael Luder-Rosefield
Is there any way we can add function/operator equivalence to the language?
Perhaps some kind of 'operators' global object with symbol fields matching
operator string to functions/constraints?
--
Dammit babies, you've got to be kind.


On Thu, 15 Aug 2019 at 08:47, Andrea Giammarchi 
wrote:

> FWIW another disadvantage is that operators cannot be polyfilled, so it'll
> take forever for those not using transpilers to adopt these, while having a
> `Math,mod` would work right away
>
> On Thu, Aug 15, 2019 at 8:40 AM Claude Pache 
> wrote:
>
>>
>>
>> Le 12 août 2019 à 22:00, Matthew Morgan  a écrit
>> :
>>
>> JS needs a modulo operator. It currently has the remainder operator `%`
>> which works in most cases except for negative values. I believe the the
>> `%%` would work great and be easy to remember.
>>
>> let x = (-13) %% 64;
>> is equivalent to
>> let x = ((-13 % 64) + 64) % 64;
>>
>>
>> Is there a strong advantage of an `%%` operator over a `Math.mod()`
>> function? There is the precedent of the `**` operator implemented as
>> alternative of `Math.pow()` few years ago. It would be interesting to hear
>> the feedback of those that use regularly powers, whether the benefit was
>> clear (personally, I almost never use either `Math.pow()` or `**`, so that
>> I can’t say anything).
>>
>> At least one disadvantage of an operator over a function, is that you
>> have to think about precedence. The problem is exacerbated in JS, because
>> (following some other languages) the unary minus has an uncanny high
>> precedence level, confusingly very different than the one of the binary
>> minus; so that, after having designed `**`, it was realised at the last
>> minute that `-a**b` would be dumbly interpreted as `(-a)**b` instead of
>> `-(a**b)` or `0-a**b`, as anybody who would be likely to actually use the
>> operator would expect. (That particular issue was resolved in a hurry by
>> making the parenthesis-left form a syntax error.)
>>
>> —Claude
>>
>> ___
>> es-discuss mailing list
>> es-discuss@mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
> ___
> 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: Proposal: Selector/Select Expression

2019-06-26 Thread Michael Luder-Rosefield
The more I read this proposal, the more I feel the ideal solution is a
preceding 'wildcard' character, to stand-in for a generic argument. If it
wasn't in (widespread!) use, I'd suggest an underscore: ```const f = _.prop
```

Since it is, though, we need another one. How about a double-colon, seeing
as it can represent property access on other languages? ```const f = ::prop
```, ```const g = ::[compProp] ```, ```const h =  ::?optProp ```

On Sun, 23 Jun 2019, 11:43 Simon Farrugia, 
wrote:

> I was expecting that someone brings up the brackets property accessor at
> some point.
> I would argue that there is a bit of syntactic inconsistency since usually
> when using the bracket accessors it is not preceded by a dot.
> ```
> const getEmail = user => user["contacts"].email; // No dot between user &
> ["contacts"].
> const getEmail = .["contacts"].email;
> ```
> Having said that, the currently proposed Optional Chaining operator
> (Stage 2)  does
> exactly that and more:
> ```
> obj?.prop   // optional static property access
> obj?.[expr] // optional dynamic property access
> func?.(...args) // optional function or method call
> ```
> So I'd say that there is consistency with what is currently being proposed.
>
> Regarding the Optional Chaining operator, which precedes the dot. How
> would that work?
>
> It would have to be something like this, if allowed.
> ```
>
> const getEmail = user => user?.contacts.email;
> const getEmail = ?.contacts.email;
>
> ```
>
> It does look odd at first, but it’s quite simple is you think about it. We
> are just omitting the initial part of the expression.
>
>
>
> More Examples with Optional Chaining operator:
>
> ```
>
> // With optional dynamic property access.
>
> const getUserEmail = user => user?.["contacts"].email;
> const getUserEmail = ?.["contacts"].email;
>
>
>
> // With optional function or method call.
>
> const getJohnsEmail = getUserContacts =>  getUserContacts
> ?.("John").email;
> const getJohnsEmail = ?.("john").email;
>
> ```
>
>
>
> The beauty of what is being proposed is that there is nothing new to learn
> or any new weird operator introduced.
>
> Any weirdness one might find with the expressions above will already have
> been introduced by the Optional Chaining operator.
>
> The only thing this does is to allow you to omit the initial (redundant)
> part of the expression.
>
>
> ___
> 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: syntactic sugar for extracting fields from objects

2019-05-26 Thread Michael Luder-Rosefield
I tried to see if I could do this in a single destructuring step, but here
is what happened:

```
var user = { profile: { firstName: 'Bob', lastName: 'Ruffward', x: 'hi' } }
var obj = { ...({firstName, lastName} = user.profile), otherData:
'otherData' }
```

So... what happened? (I'm sure you all know already)

`obj` ended up with _all_ of `user.profile`'s properties:
```
{ firstName: "Bob", lastName: "Ruffward", x: "hi", otherData: "otherData" }
```
and `firstName` and `lastName` were assigned as global variables.

```
firstName \\ "Bob"
lastName \\ "Ruffward"
```

--
Dammit babies, you've got to be kind.


On Sun, 26 May 2019 at 15:56, Григорий Карелин  wrote:

> Yep, in the same way as destructuring would work
>
> вс, 26 мая 2019 г. в 17:52, guest271314 :
>
>> If not found in source ```firstName``` and/or ```lastName``` would be
>> assigned the value ```undefined```?
>>
>> On Sun, May 26, 2019 at 1:40 PM Григорий Карелин 
>> wrote:
>>
>>> Wouldn't it be nice to have syntax like this:
>>> const obj = { {firstName, lastName from user.profile}, otherData: 'other
>>> data'  };
>>> as a syntactic sugar for
>>> const obj = {firstName: user.profile.firstName, lastName:
>>> user.profile.lastName, otherData: 'other data'};
>>>
>>> Of cause at the moment we can write it in two steps:
>>> const {fistName, lastName} = userProfile;
>>> const obj = {firstName, lastName, otherData: 'other data'}
>>>
>>> But why use extra variables?
>>>
>>> Motivating example is lodash's .pick() method:
>>> https://lodash.com/docs/#pick
>>> ___
>>> 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: Swift style syntax

2019-05-07 Thread Michael Luder-Rosefield
I've always been partial to operators merely being functions with
infix/whatever sugar; having operators without there being a corresponding
function seems deeply weird.
--
Dammit babies, you've got to be kind.


On Tue, 7 May 2019 at 05:58, Ates Goral  wrote:

> This topic has been discussed a long time ago and has stalled on
> discussions of a standard library.
>
> Coming back to the idea of adding some basic math operations directly
> on Math, there could be value in adding at least the following (from
> Isiah Meadows's post):
>
> > - `a + b` -> `Math.add` -> `:+`
> > - `a - b` -> `Math.sub` -> `:-`
> > - `a * b` -> `Math.mul` -> `:*` (different from `imul`)
> > - `a / b` -> `Math.div` -> `:/`
>
> `Math.add`: Among potentially other things, this could be useful for
> an out-of-the-box, terse way to add up items in an array. So, instead
> of:
>
> ```
> array.reduce((sum, item) => sum + item);
> ```
>
> Items could be added up with:
>
> ```
> array.reduce(Math.add);
> ```
>
> `Math.sub`: Among potentially other things, this could be useful for
> sorting numbers without having to define a custom comparator (i.e. almost
> as
> an out-of-the-box riposte to the "JavaScript WTF" refrain of
> lexicographically sorting numbers by using the default sort
> implementation.) So, instead of:
>
> ```
> array.sort((first, second) => first - second);
> ```
>
> Numbers could be sorted with:
>
> ```
> array.sort(Math.sub);
> ```
>
> `Math.mul` and `Math.div`: I don't have a compelling use case in mind,
> but I'd just throw these in for good measure / symmetry.
>
> Ates
> ___
> 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: Swift style syntax

2019-05-07 Thread Michael Luder-Rosefield
--
Dammit babies, you've got to be kind.


On Tue, 7 May 2019 at 05:58, Ates Goral  wrote:

> This topic has been discussed a long time ago and has stalled on
> discussions of a standard library.
>
> Coming back to the idea of adding some basic math operations directly
> on Math, there could be value in adding at least the following (from
> Isiah Meadows's post):
>
> > - `a + b` -> `Math.add` -> `:+`
> > - `a - b` -> `Math.sub` -> `:-`
> > - `a * b` -> `Math.mul` -> `:*` (different from `imul`)
> > - `a / b` -> `Math.div` -> `:/`
>
> `Math.add`: Among potentially other things, this could be useful for
> an out-of-the-box, terse way to add up items in an array. So, instead
> of:
>
> ```
> array.reduce((sum, item) => sum + item);
> ```
>
> Items could be added up with:
>
> ```
> array.reduce(Math.add);
> ```
>
> `Math.sub`: Among potentially other things, this could be useful for
> sorting numbers without having to define a custom comparator (i.e. almost
> as
> an out-of-the-box riposte to the "JavaScript WTF" refrain of
> lexicographically sorting numbers by using the default sort
> implementation.) So, instead of:
>
> ```
> array.sort((first, second) => first - second);
> ```
>
> Numbers could be sorted with:
>
> ```
> array.sort(Math.sub);
> ```
>
> `Math.mul` and `Math.div`: I don't have a compelling use case in mind,
> but I'd just throw these in for good measure / symmetry.
>
> Ates
> ___
> 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 For A New Alternative Keyword To “this” For Classes

2019-03-19 Thread Michael Luder-Rosefield
I'm getting deja vu again

On Tue, 19 Mar 2019 at 14:31 Isiah Meadows  wrote:

> UX workflows aren't all of JS. Classes exist for many more reasons than
> that, and 99% of my classes are for abstracting non-trivial business logic
> and ensuring *those* are easily testable, not directly UI/UX.
>
> -
>
> Isiah Meadows
> cont...@isiahmeadows.com
> www.isiahmeadows.com
>
>
> On Sun, Mar 17, 2019 at 2:35 AM kai zhu  wrote:
>
>> *rant warning*
>>
>> -1 because classes generally have little-value in UX-workflow programming.
>>
>> the example class RequestManager (given in this discussion),
>> realistically has little reusability-value -- its no better than employing
>> a throwaway static-function (both are equally likely to get rewritten each
>> time UX-workflow features are added.).
>>
>> for example, a common feature-request is adding visual-progress-bar.
>>  there is no "simple" way to extend RequestManager to do this, other than
>> significant-refactoring of the base-class (and risk breaking
>> class-dependencies downstream).
>>
>> some other common UX feature-requests that would likely invalidate
>> "reusability" of your class-based design include:
>>
>> 1. needing to upload a binary-file (social-images, receipt-signatures,
>> screenshots, etc...)
>> 2. needing to upload multiple binary-files in parallel (keeping track of
>> timeouts of each)
>> 3. needing to upload multiple binary-files in parallel (keeping track of
>> timeouts of each),
>> and then download their thumbnail-previews from server to visually
>> confirm uploads were correct
>> 4. needing to make parallel http-requests from 3rd-party sources and
>> "joining" the response-data
>> 5. needing the sign-up-page to additionally pre-validate
>> email / username / mobile-number / credit-card / etc... before
>> form-submission to server
>>
>> many frontend-engineers with experience "extending" products with
>> additional UX-workflow features, know its rarely as simple as modifying
>> some class-methods and be done with it -- it oftentimes require rewriting
>> nearly every-piece-of-code that touches the given workflow needing
>> enhancement.
>>
>> p.s. -- here's a "simple" fully-working UX-example [1] on how to add
>> visual-progress-bar to http-requests.  if i had to additionally add some of
>> the other UX-features mentioned above, it would likely entail me completely
>> rewriting the throwaway static-function, rather than waste time trying to
>> extend it.
>>
>> [1] https://jsfiddle.net/kaizhu256/t9ubdenf/
>>
>> ```html
>> 
>> /* jslint utility2:true */
>> /* csslint ignore:start */
>> *,
>> *:after,
>> *:before {
>> box-sizing: border-box;
>> }
>> /* csslint ignore:end */
>> body {
>> background: #eee;
>> font-family: Arial, Helvetica, sans-serif;
>> font-size: small;
>> }
>> input {
>> width: 100%;
>> }
>> textarea {
>> font-family: Consolas, Menlo, monospace;
>> font-size: smaller;
>> overflow: auto;
>> width: 100%;
>> }
>> 
>>
>> 
>>
>> ajax-request
>> {
>> "method": "GET",
>> "url": "https://api.github.com/orgs/octokit/repos;,
>> "headers": {
>> "accept": "application/vnd.github.v3+json"
>> },
>> "data": "hello world!"
>> }
>>
>> submit ajax-request
>>
>> ajax-response
>> 
>>
>> 
>> /*jslint browser*/
>> (function () {
>> "use strict";
>> var local;
>> local = {};
>> window.local = local;
>>
>> local.ajax = function (opt, onError) {
>> /*
>>  * simple, throwaway ajax-function that can be easily rewritten
>>  * to accomodate new [async] ux-features
>>  */
>> var resHandler;
>> var xhr;
>> opt.headers = opt.headers || {};
>> opt.method = opt.method || "GET";
>> xhr = new XMLHttpRequest();
>> // open url
>> xhr.open(opt.method, opt.url);
>> // set req-headers
>> Object.entries(opt.headers).forEach(function (entry) {
>> xhr.setRequestHeader(entry[0], entry[1]);
>> });
>> // send data
>> xhr.send(opt.data);
>> // init request-handling
>> resHandler = function (evt) {
>> /*
>>  * this function will handle ajax-response
>>  */
>> switch (evt.type) {
>> case "abort":
>> case "error":
>> // decrement ajaxProgressCounter
>> local.ajaxProgressCounter = Math.max(
>> local.ajaxProgressCounter - 1,
>> 0
>> );
>> onError(new Error(evt.type), xhr);
>> break;
>> case "load":
>> // decrement ajaxProgressCounter
>> local.ajaxProgressCounter = Math.max(
>> local.ajaxProgressCounter - 1,
>> 0
>> );
>> onError(null, xhr);
>> break;
>> }
>> // increment ajax-progress-bar
>> 

Re: Proposal For A New Alternative Keyword To “this” For Classes

2019-03-09 Thread Michael Luder-Rosefield
How about binding `this` to a variable in the constructor? The following
syntax throws an error due to `this` being a reserved word, so won't break
any existing code:

```
class Foo {
  constructor (this: self, /* normal args */) {
// ...
  }
}
```

I can see arguments against that as it breaks the convention for how
parameter lists work, and also requires a constructor. Perhaps, then, we
could either use something like a modified version of class field
declarations to make class variables:

```
class Foo {
  const self = this;
  // ...
}
```

Or, maybe, allow parentheses before the class body to define variables:

```
class Foo (this: self) {
  //...
}
```

No, I don't like that one either.

The second suggestion (class variables as extension of class fields
proposal) seems like it has potential to me, so it seems like an excellent
time for everyone here to tell me why it's awful and stupid.

On Sun, 10 Mar 2019 at 06:59 Jordan Harband  wrote:

> The engine only has that knowledge when you call it in `a.b()` form - at
> which point, `this` is already the instance. For a keyword to not be
> context dependent, it'd have to be the instance even when you'd done
> something like `const { b } = a; b()`. To do this would require either a)
> `a` has its own distinct copy of `b` that's bound to `a`, or b) `a.b` to be
> a getter that does that binding upon request.
>
> Constructor-binding, field-binding, or arrow function fields all work the
> same way - they create a separate copy of a function for *each and every*
> instance, so that the function can point back to the instance even when
> extracted off of the object.
>
> I'm not clear on how there'd be any other way to do it.
>
> On Sat, Mar 9, 2019 at 1:41 PM john larson 
> wrote:
>
>> Although the method lives on the prototype, the engine should already
>> have knowledge of the object whose method is being invoked. I am not an
>> expert on the internal workings of the engine, so I would be glad if anyone
>> would correct me on this if I am wrong.
>>
>>
>> 
>>  Virus-free.
>> www.avast.com
>> 
>> <#m_6849901573705770350_m_-8660865756228832385_DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
>>
>> On Sun, Mar 10, 2019 at 12:27 AM Jordan Harband  wrote:
>>
>>> An additional keyword like this would require a function to have a
>>> hidden reference back to the instance. However, especially for `class`
>>> methods, but also for ES5-style inheritance, or even for `class Foo {}
>>> Foo.prototype.bar = function () {}`, methods are *shared*. You might have a
>>> billion instances, but only one function that uses your new keyword - how
>>> would the engine know which instance you were referring to?
>>>
>>> On Sat, Mar 9, 2019 at 7:50 AM Bergi  wrote:
>>>
 Hi John,

 > I believe that it would be a trivial task for
 > current static code analyzers to restrict usage of "this" for anyone
 > opting in to use this new keyword exclusively.

 Static tooling, like the TypeScript compiler, can detect problematic
 method usage already today. Sure, having a dedicated syntax for this
 will make static analysis simpler, but I don't deem that a worthy
 addition to the language.

 > As you mentioned, arrow functions might have their own
 > problems. Wouldn't such an alternative keyword be a good addition to
 our
 > toolkit anyway?

 What I was trying to say is that your proposed alternative has exactly
 the same problems as instance-member arrow functions have today.

 Best regards,
   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
>
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Chainable do sugar

2019-01-17 Thread Michael Luder-Rosefield
It's OK, you can say the m-word here. Monad. See? Nothing bad wi--

-TRANSMISSION LOST

On Fri, 18 Jan 2019 at 11:03 Paul Gray  wrote:

> Hello friends!
>
> I’d love to discuss the potential for syntax sugar around a popular fp
> pattern, *chainables*!
>
> I’ve written up a document here
>  with the
> details.
>
> I’ve also written a small Babel plugin that implements this. Here’s a
> codesandbox  with it loaded up.
>
> Thanks for your time!
>
> - Paul Gray
> ___
> 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: String identity template tag

2018-12-11 Thread Michael Luder-Rosefield
Why not String.tag or .tagged?

While we're at it, is there any good reason not to have something like this:

```
String.template = (template : String, taggerFn=String.identity/tag/tagged :
Function) => (keys : Array | Object) => taggerFn(template, (keys is Array)
? ...keys : keys)
// apologies for pseudo-semi-functional code
// having keys be an object allows template to be filled by key name rather
than just index
```
This would make templates closer to the traditional usage, where the
template comes first and is later passed values to be filled in with.
Having the taggerFn as an argument allows for things like Isiah's
escape-then-apply tagging examples.


On Wed, 12 Dec 2018 at 12:51 Isiah Meadows  wrote:

> I'm not married to `identity`, and I agree the name is probably not
> ideal. I'm more concerned about functionality, though.
>
> -
>
> Isiah Meadows
> cont...@isiahmeadows.com
> www.isiahmeadows.com
>
> On Tue, Dec 11, 2018 at 5:41 AM T.J. Crowder
>  wrote:
> >
> > On Mon, Dec 10, 2018 at 7:08 PM Isiah Meadows
> >  wrote:
> > >
> > > It'd be *way* easier to construct simple template tags if there was a
> > > built-in identity tag
> >
> > Wholeheartedly agree, a couple of months ago I considered posting
> something very similar, both for utility reasons and in hopes that it would
> be an optimization target (being a standard operation).
> >
> > I find the name `identity` unilluminating, though, partially because
> it's not quite the same meaning as the usual "identity" function (`function
> identity(x) { return x; }`), though it's close. `assemble`?
> >
> > -- T.J. Crowder
> ___
> 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 for faster this assignments in constructor functions

2018-12-01 Thread Michael Luder-Rosefield
``this = { ...this, par1, par2, par3 }```

Oh, wait, I'm going to point out the problem with what I wrote before
anyone else does: this will lose any non-enumerable properties on `this`,
which in a class instance is kind of a big no-no. `Object.assign` is better
here.

On Sat, 1 Dec 2018 at 20:08 Michael Luder-Rosefield 
wrote:

> > ```js
> this.{} = {par1, par2, par3};
> ```
>
> Of course, that could be expressed as ```this = { ...this, par1, par2,
> par3 }```, but that's still a bit verbose.
>
> I already know this is going to get dismissed for changing the way the `+`
> operator works, but it strikes me that a better way of expressing that
> might be ```this += { par1, par2, par3 }```.
>
> That naturally leads to having ```obj1 + obj2 === Object.assign(obj1,
> obj2)``` and ```arr1 + arr2 === (arr1 = [ ...arr1, ...arr2 ])```, which
> would be good except for the whole breaking-change thing.
>
> On Fri, 30 Nov 2018 at 22:52 Simo Costa  wrote:
>
>> Thank you T.J. Crowder for giving me your opinion on this proposal.
>> I didn't know about the Bob Myers' for pick notation and it isn't bad.
>>
>> I still prefer something like that:
>> ```js
>> constructor(this.{par1, par2, par3}) {
>> }
>> ```
>>
>> but this doesn't sound bad to me:
>>
>> ```js
>> constructor(par1, par2, par3) {
>> this.{} = {par1, par2, par3};
>> }
>> ```
>>
>> There is still a repetition, but it is a a step forward.
>>
>> Il giorno gio 29 nov 2018 alle ore 12:28 T.J. Crowder <
>> tj.crow...@farsightsoftware.com> ha scritto:
>>
>>> On Wed, Nov 28, 2018 at 6:33 PM Simo Costa
>>>  wrote:
>>> >
>>> > So my proposal is to avoid those repetitions...
>>>
>>> I'm a bit surprised to find that no one's mentioned Bob Myers'
>>> [proposal][1] for pick notation yet, which would readily address this
>>> requirement *and* various other requirements beyond initializing
>>> newly-constructed objects.
>>>
>>> Using Bob's current draft syntax, Simo's example would be:
>>>
>>> ```js
>>> constructor(par1, par2, par3) {
>>> this.{par1, par2, par3} = {par1, par2, par3};
>>> }
>>> ```
>>>
>>> or if the constructor accepts an object:
>>>
>>> ```js
>>> constructor(options) {
>>> this.{par1, par2, par3} = options;
>>> }
>>> ```
>>>
>>> But I think we can go further if we tweak the syntax a bit. Perhaps:
>>>
>>> ```js
>>> constructor(par1, par2, par3) {
>>> this.{} = {par1, par2, par3};
>>> }
>>> ```
>>>
>>> ...where the property names are inferred from the properties on the
>>> right-hand side. That would be functionally equivalent to:
>>>
>>> ```js
>>> constructor(par1, par2, par3) {
>>> Object.assign(this, {par1, par2, par3});
>>> }
>>> ```
>>>
>>> ...but since the syntax is clear about the intent, when an object
>>> initializer (rather than just object reference) is used on the right-hand
>>> side it's an optimization target if a constructor is "hot" enough to
>>> justify it (e.g., an engine could optimize it into individual assignments).
>>>
>>> For me, that would be a great, clear, concise feature, and hits the
>>> other use cases Bob mentions in his proposal. I like that I'm still in
>>> control of what parameters get assigned as properties (which I think has
>>> been true of all of the suggestsions in this thread).
>>>
>>> -- T.J. Crowder
>>>
>>> [1]: https://github.com/rtm/js-pick-notation
>>>
>> ___
>> 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 for faster this assignments in constructor functions

2018-12-01 Thread Michael Luder-Rosefield
> ```js
this.{} = {par1, par2, par3};
```

Of course, that could be expressed as ```this = { ...this, par1, par2, par3
}```, but that's still a bit verbose.

I already know this is going to get dismissed for changing the way the `+`
operator works, but it strikes me that a better way of expressing that
might be ```this += { par1, par2, par3 }```.

That naturally leads to having ```obj1 + obj2 === Object.assign(obj1,
obj2)``` and ```arr1 + arr2 === (arr1 = [ ...arr1, ...arr2 ])```, which
would be good except for the whole breaking-change thing.

On Fri, 30 Nov 2018 at 22:52 Simo Costa  wrote:

> Thank you T.J. Crowder for giving me your opinion on this proposal.
> I didn't know about the Bob Myers' for pick notation and it isn't bad.
>
> I still prefer something like that:
> ```js
> constructor(this.{par1, par2, par3}) {
> }
> ```
>
> but this doesn't sound bad to me:
>
> ```js
> constructor(par1, par2, par3) {
> this.{} = {par1, par2, par3};
> }
> ```
>
> There is still a repetition, but it is a a step forward.
>
> Il giorno gio 29 nov 2018 alle ore 12:28 T.J. Crowder <
> tj.crow...@farsightsoftware.com> ha scritto:
>
>> On Wed, Nov 28, 2018 at 6:33 PM Simo Costa
>>  wrote:
>> >
>> > So my proposal is to avoid those repetitions...
>>
>> I'm a bit surprised to find that no one's mentioned Bob Myers'
>> [proposal][1] for pick notation yet, which would readily address this
>> requirement *and* various other requirements beyond initializing
>> newly-constructed objects.
>>
>> Using Bob's current draft syntax, Simo's example would be:
>>
>> ```js
>> constructor(par1, par2, par3) {
>> this.{par1, par2, par3} = {par1, par2, par3};
>> }
>> ```
>>
>> or if the constructor accepts an object:
>>
>> ```js
>> constructor(options) {
>> this.{par1, par2, par3} = options;
>> }
>> ```
>>
>> But I think we can go further if we tweak the syntax a bit. Perhaps:
>>
>> ```js
>> constructor(par1, par2, par3) {
>> this.{} = {par1, par2, par3};
>> }
>> ```
>>
>> ...where the property names are inferred from the properties on the
>> right-hand side. That would be functionally equivalent to:
>>
>> ```js
>> constructor(par1, par2, par3) {
>> Object.assign(this, {par1, par2, par3});
>> }
>> ```
>>
>> ...but since the syntax is clear about the intent, when an object
>> initializer (rather than just object reference) is used on the right-hand
>> side it's an optimization target if a constructor is "hot" enough to
>> justify it (e.g., an engine could optimize it into individual assignments).
>>
>> For me, that would be a great, clear, concise feature, and hits the other
>> use cases Bob mentions in his proposal. I like that I'm still in control of
>> what parameters get assigned as properties (which I think has been true of
>> all of the suggestsions in this thread).
>>
>> -- T.J. Crowder
>>
>> [1]: https://github.com/rtm/js-pick-notation
>>
> ___
> 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: Numeric Array prototypes

2018-11-20 Thread Michael Luder-Rosefield
> Math.min() method doesn't work on Arrays right out of the box.

No, but rest parameters work: Math.min(...arr) is fine, and works with Sets
too.



On Wed, 21 Nov 2018 at 14:08 Isiah Meadows  wrote:

> Not sure these belong in the standard library itself. I could see max and
> min being there (these are very broadly useful), but the others, not so
> much. I'd also like both max and min accept an optional comparison callback
> of `(a, b) => a < b`. But the rest seem too narrowly useful IMHO.
> On Tue, Nov 20, 2018 at 21:38 Gbadebo Bello 
> wrote:
>
>> The array object has no method for finding the minimum value of an array
>> of numbers and the Math.min() method doesn't work on Arrays right out of
>> the box. I'll have similar issues if i wanted to return the maximum number,
>> the mean, mode,  median or standard deviations in any array of numbers.
>>
>> This is a bit tasky and can be done in just a line of code if there where
>> Array.prototype.{method}() for it.
>>
>> My proposal is, Arrays should have the following prototypes
>>
>>1. Array.prorotype.min()
>>2.  Array.prorotype.max()
>>3. Array.prorotype.mean()
>>4. Array.prorotype.median()
>>5. Array.prorotype.mode()
>>6. Array.prototype.stdev()
>>
>> The mean, median and mode would be very useful when visuali
>> Here's is a polyfill of what i'll love to propose.
>>
>> //Array.prototype.min()
>> Array.prototype.min = function(){
>> let arrayVal = this;
>> let checkNonNumbers = this.some(element => {
>> if(typeof(element) !== typeof(Math.random())){
>> throw new Error("This Array.prorotype.min() takes only array of numbers
>> as arguments");
>> }
>> else{
>> return true;
>> }
>> });
>> function findMin(validated){
>> if(validated == true){
>> return Math.min.apply( Math, arrayVal );
>> }
>> }
>> return findMin(checkNonNumbers);
>> }
>>
>> Similarly, Array.prototype.max() can be implemented as above.
>>
>>
>>
>> //Array.prototype.median()
>> Array.prototype.median = function(){
>> let values = this;
>> function median(values){
>> values.sort(function(a,b){
>> return a-b;
>> });
>> if(values.length ===0) return 0
>> var half = Math.floor(values.length / 2);
>> if (values.length % 2)
>> return values[half];
>> else
>> return (values[half - 1] + values[half]) / 2.0;
>> }
>> return median(numbers)
>> }
>> ___
>> 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: await enhancement proposal: Wrap Array return values with Promise.all

2018-09-24 Thread Michael Luder-Rosefield
Would it be possible to extend `await` such that you could `await.all()`?

If not, one minor thing that might help cut down the noise (if it works
with native Promises without this-binding; I've done it with RSVP):

```
const { all } = Promise;

await all(/* */);
```

On Sun, 23 Sep 2018, 02:53 Logan Smyth,  wrote:

> Making `await` itself do this would be a breaking change, so that'd be
> very unlikely. There was discussion around an `await*` similar to the
> existing `yield*` for generators, but I think it was deemed unneeded
> complexity since `Promise.all` was already pretty easy to use, especially
> since it isn't 100% obvious from the usage of an array what should be done.
> For instance `Promise.race` also works on an iterable value. I'm not really
> involved with the process, so I can't say more though.
>
> On Sat, Sep 22, 2018 at 12:25 AM Rudi Cilibrasi 
> wrote:
>
>> Greetings,
>>
>> I have enjoyed using the `await` keyword tremendously in async code. One
>> point I notice in using it is that it is ideal in terms of clarity and
>> composability but limited in a sense to sequential composition. That is, I
>> cannot easily use `await` (by itself) to do parallel calculations.
>>
>> A few times, I have myself hit a bug where I return (without thinking) an
>> Array of Promise only to find that none will resolve using `await` on the
>> Array. I noticed others have similar bugs. [1,2] I frequently wind up
>> wrapping them in one of two ways: a) occasionally a for loop that awaits
>> each in sequence, but b) more often a `Promise.all`. I think the current
>> `await` syntax makes every kind of sequential composition quite simple to
>> read, write, and maintain, but the fact that we have to introduce
>> `Promise.all` for each case of parallel (overlapping) execution seems to be
>> a common cause of bugs and a minor aesthetic issue to me as well as perhaps
>> maintenance. It occurs to me that for my cases, and indeed perhaps others,
>> a useful rule would be that all `await` on `Array` behave as if the Array
>> were wrapped in `Promise.all`.  Then we can have a nice parallel
>> composition syntax built into the language with the keyword using Array and
>> lists can become idiomatic and concise parallel composition operators. I
>> feel like this could improve the readability, power, and real time
>> responsiveness of the language without necessarily sacrificing quality nor
>> clarity.
>>
>> await on an Array value v acts as await Promise.all(v)
>>
>> Weighing against this idea seems to be the usual: operator tricks are
>> unsearchable via keywords compared to `Promise.all`. So there is a style
>> question however with the latest addition of the great new
>> optional-chaining and pipeline ideas I thought it might be a good time to
>> give this idea a try.
>>
>> What does the group think about this await enhancement proposal?
>>
>> Best regards,
>>
>> Rudi Cilibrasi
>>
>> [1]:
>> https://stackoverflow.com/questions/38694958/javascript-async-await-for-promises-inside-array-map
>> [2]:
>> https://stackoverflow.com/questions/37360567/how-do-i-await-a-list-of-promises-in-javascript-typescript
>>
>> --
>> Happy to Code with Integrity : Software Engineering Code of Ethics and
>> Professional Practice 
>> ___
>> 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: const {resolve} = Promise; // fails

2018-07-19 Thread Michael Luder-Rosefield
At this point I can't ignore how much overlap there is between this and the
this-binding operator proposal
https://github.com/tc39/proposal-bind-operator

```
const resolve = ::Promise.resolve; // takes and binds
```

As someone who often extracts functions with deconstruction, I'd love for
there to be an extension to this proposal to handle this case.

```
const { resolve, reject } = ::Promise; // ?
```

That would leave the question though of what to do with nesting:

```
const { fn1, foo: { fn2 } } = ::bar; // fn1 is bound to bar. Is fn2 bound
to bar, or foo?
```

On Thu, 19 Jul 2018 at 15:58 Andrea Giammarchi 
wrote:

> I guess one example would be more explicative: why cannot public static
> methods be defined in a similar manner?
>
> ```js
> const withLazyBoundObjects = new WeakMap;
> const withLazyBoundMethods = obj => {
>   const descriptors = Object.getOwnPropertyDescriptors(obj);
>   Object.keys(descriptors).forEach(key => {
> const desc = descriptors[key];
> const {value} = desc;
> if (desc.configurable && typeof value === 'function') {
>   delete desc.value;
>   delete desc.writable;
>   desc.get = function (...args) {
> let methods = withLazyBoundObjects.get(this || obj);
> if (!methods)
>   withLazyBoundObjects.set(this, methods = Object.create(null));
> return methods[key] || (methods[key] = value.bind(this));
>   };
> }
>   });
>   return Object.defineProperties(obj, descriptors);
> };
>
> // example
> const {resolve, reject} = withLazyBoundMethods(Promise);
> resolve(123).then(console.log);
> ```
>
> On Thu, Jul 19, 2018 at 4:33 PM Andrea Giammarchi <
> andrea.giammar...@gmail.com> wrote:
>
>> sorry, that'd be `public get resolve()` and also `public #resolve()` so
>> nobody should be confused about the fact I'm talking about public static
>> methods.
>>
>> On Thu, Jul 19, 2018 at 4:32 PM Andrea Giammarchi <
>> andrea.giammar...@gmail.com> wrote:
>>
>>> I know it's about subclassing, which is why I've asked why, once there's
>>> no context, the default/base one is not considered, but since everyone came
>>> back with the subclassing issue, which is actually what I've said myself on
>>> twitter about the current state, how about changing all public static
>>> methods that need it, to be getters ?
>>>
>>> ```js
>>> class Promise {
>>>   #resolve(...args) {
>>> return this.nativeImplementation(...args);
>>>   }
>>>   get resolve() {
>>> return #resolve.bind(this);
>>>   }
>>> }
>>> ```
>>>
>>> we could argue `Promise.resolve === Promise.resolve` should be
>>> preserved, as behavior, so that we need a lazy defined getter ... **but**
>>> why not making public static restructuring from known constructors work
>>> regardless, under all circumstances ?
>>>
>>>
>>> On Thu, Jul 19, 2018 at 4:11 PM T.J. Crowder <
>>> tj.crow...@farsightsoftware.com> wrote:
>>>
 On Thu, Jul 19, 2018 at 12:56 PM, Andrea Giammarchi
  wrote:
 > Why cannot Promise methods fallback to Promise constructor when the
 > class/context is not available?

 That sounds reasonable on first glance, but I'd be concerned about what
 happens when you do it after subclassing:

 ```js
 class MyPromise extends Promise {
 // ...and adds some important feature...
 }
 // ...
 const {resolve, reject} = MyPromise;
 const p = resolve();
 p.someImportantFeature(/*...*/); // TypeError: undefined is not a
 function
 ```

 ...since `resolve` fell back to `Promise`. That feels like a footgun.
 Either subclassers would have to handle that, which they will forget to do,
 or it has to be a bit more complicated than just a simple fallback to `
 Promise` (I don't immediately know what that "more complicated" answer
 would be.)

 -- T.J. Crowder

 ___
> 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: const {resolve} = Promise; // fails

2018-07-19 Thread Michael Luder-Rosefield
I'd reinforce this with the fact that this works for RSVP.js
https://github.com/tildeio/rsvp.js/, and so the current behaviour is a
potential breaking point if code is being converted to use native Promises.

On Thu, 19 Jul 2018 at 12:56 Andrea Giammarchi 
wrote:

> As quickly discussed on Twitter, it's very inconvenient and inconsistent
> that the following fails:
>
> ```js
> const {resolve, reject} = Promise;
>
> resolve(123); // throws
> ```
>
> Compared to every other public static method in ECMAScript that works,
> including those methods that might need the contextual class, as it is for
> the Array.from case.
>
> ```js
> const {from} = Array;
>
> from({0: 'abc', length: 1}); // ["abc"] // all good
> ```
>
> Why cannot Promise methods fallback to Promise constructor when the
> class/context is not available?
>
> Wouldn't be simple/reasonable change to make so that developers
> expectations would be preserved?
>
> Best Regards.
> ___
> 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: Feature proposal

2018-07-19 Thread Michael Luder-Rosefield
This array view thing is very close to what I had in mind, and seems to
suggest to a lot of interesting possibilities.

What strikes me as the two most significant are:

   - again, 'reversed' is just one alternative iteration order through,
   though almost certainly the most useful
   - others I can think of could be 'even/odd indexes', 'random shuffle',
  'iterate-until /while-condition', and filter equivalents
   - as well as the view defining the iteration order, it could define the
   computed value
  - this would be basically a map where the value isn't computed until
  accessed; caching behaviour could be user-determined




On Thu, 19 Jul 2018 at 09:49 Isiah Meadows  wrote:

> What about this alternate proposal:
>
>
> https://github.com/isiahmeadows/array-additions-proposal/blob/master/README.md#get-arrayprototypereversed-get-typedarrayprototypereversed
>
> (I've got a myriad of other related stuff there, too.)
>
>
> On Thu, Jul 19, 2018, 04:41 Dmitry Shulgin  wrote:
>
>> Above we was talking about this.
>> consistency and handy using -- two main reasons for this proposal.
>>
>> `reverse` will also mutate my array, cause of in-place implementation.
>>
>> You can find workaround for many existing methods, but it's not handy to
>> my mind.
>>
> ___
> 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: Feature proposal

2018-07-18 Thread Michael Luder-Rosefield
Is strikes me that every single Array method that takes an iteratee
function (signature (value, index, array)) should be able to iterate
through the array in reverse, in a standardised way.

At the moment, we have:

   - every
   - filter
   - find
   - findIndex
   - forEach
   - indexOf / lastIndexOf
   - map
   - reduce / reduceRight
   - some

which is not very consistent at all. Perhaps we could add an `iterOrder`
method that changes the way the array is iterated through?

I propose it could take 1 parameter:

   - If -1 is passed in, the array is iterated through in reverse.
   - If 1,0 or undefined is passed through, the array is iterated through
   normally.
   - If an array of numbers is passed through, these represent the indexes
   in the order they will be processed.
   - Any illegible indexes in the passed-in array will be ignored
  - Any eligible indexes not given will be ignored
   - If a generator function is passed in, it should take the array (or a
   length value) and spit out indexes.
   - If a non-generator function is passed in, it should spit out an array
   of indexes, which will be used as-per arrays being passed in

Whether that iterOrder is reset after an iteration could go either way. I'd
suggest it probably should, with an option to persist.

Example:

```
let arr = [ 8,4,7,3 ];

arr.iterOrder().map(x => x) === arr
arr.iterOrder(-1).map(x => x) === arr.reverse() === [ 3,7,4,8 ]
arr.iterOrder([ 2,1 ]).map(x => x) === [ 7,4 ]
// haven't got time to give function arg examples, but randomisers would be
fairly trivial

// original indexes are preserved during iteration:
arr.iterOrder(-1).forEach((val, i) => console.log(val, i))
// > 3, 3
// > 7, 2
// > 4, 1
// > 8, 0
```

This is a messy first-pass at the problem, and I can already see potential
issues, but it would at least standardise and generalise the problem



On Wed, 18 Jul 2018 at 17:44 Cyril Auburtin 
wrote:

> sorry you get 1, and need again to subtract the array length, `arr.length
> -1 - 1` to get the final result 3
>
> Le mer. 18 juil. 2018 à 18:41, Cyril Auburtin 
> a écrit :
>
>> there you go
>> ```
>> console.log([7, 4, 6, 7, 12].findIndex((_, i, a) =>
>> isPrime(a[a.length-1-i]))); // 3
>> ```
>>
>> Le mer. 18 juil. 2018 à 11:17, Dmitry Shulgin  a
>> écrit :
>>
>>>
>>> -- Forwarded message --
>>> From: Dmitry Shulgin 
>>> Date: 2018-07-05 10:36 GMT+03:00
>>> Subject: Feature proposal
>>> To: es-discuss@mozilla.org
>>>
>>>
>>> I came across a task of finding an index of the last element in array
>>> that satisfies the condition, so i reversed array and found it by *findIndex
>>> *function.
>>> I was thinking:
>>> Why do we have *findIndex*` method, but no *findLastIndex*?
>>> It seems logical to follow *[index|lastIndex]Of* pair, doesn't it?
>>> Reversing array in this case seems too complicated to me.
>>>
>>> So, i would like to suggest new method like
>>> *Array.prototype.findLastIndex()*
>>>
>>> Example:
>>>
>>> function isPrime(element, index, array) {
>>>   var start = 2;
>>>   while (start <= Math.sqrt(element)) {
>>> if (element % start++ < 1) {
>>>   return false;
>>> }
>>>   }
>>>   return element > 1;
>>> }
>>>
>>> console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
>>> console.log([7, 4, 6, 7, 12].findIndexLast(isPrime)); // 3
>>>
>>>
>>> Would be glad to implement, if it makes sense.
>>>
>>> Thx for replies.
>>>
>>> P.S. Small issue on GitHub was closed due to offtop (not an issue, as i
>>> understand).
>>> https://github.com/tc39/ecma262/issues/1253
>>>
>>> ___
>>> 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] ignoreCase method

2018-06-27 Thread Michael Luder-Rosefield
Would it not be simpler to simply change the signature from
`function(value, arrayOfStrings)` to `function(...values)`?

I'd also suggest that a better, more general purpose formulation of
comparing a string against multiple values might be to use #match.
Something like:

```
const checkString = (str, { ignoreCase, startsWith, endsWith, equals }={} )
=> {
const start = startsWith || equals ? '^' : '';
const end = endsWith || equals ? '$' : '';
const rx = v => new RegExp(`${start}${v}${end}`,ignoreCase && 'i');

return { against: (...values) => values.some(value => str.match(rx(value)))
};
}
```


On Wed, 27 Jun 2018 at 11:50 Robert Wozniak 
wrote:

> Hi everyone,
>
> ignoreCase - JavaScript proposal
>
> It's a proposal to implement a new function to compare two strings but
> without case sensitivity.
>
> The proposal is bringing an important function, which is being used in
> Java. Many times in my career I had to compare two strings but ignore case
> sensitivity.
>
> I had to convert it first and then I could compare. I'd like developers to
> be able to use the function and compare two strings without worrying about
> case sensitivity.
> 1. Syntax
>
> String.prototype.ignoreCase = function(value, arrayOfStrings) {
> var secondOption = value.toLowerCase() || 
> arrayOfStrings.join(',').toLowerCase().split(',');
> var firstOption = this.valueOf().toLowerCase();
> if(typeof secondOption === 'object') {
> for(var i = 0, l = arrayOfStrings.length; i < l; i++) {
> if(firstOption === secondOption[i]) {
> return true;
> break;
> }
> }
> } else {
> if(firstOption === secondOption) {
> return true;
> } else {
> return false;
> }
> }
> };
>
> Above code presents *ignoreCase* function and what's happening inside.
>
> The function takes two parameters:
>
> (value, arrayOfStrings)
> 1.1
> "value" parameter
>
> The value parameter is the string which is going to be compared with the
> parent string chosen by the developer, for example:
>
> const stringOne = "Matheus";stringOne.ignoreCase("matheus"); // true;
>
> 1.2
> "arrayOfStrings" parameter
>
> The "arrayOfStrings" parameter is an array of strings, which are going to
> be compared with the parent string chosen by the developer. Once the parent
> string equals one of the strings in an array, it will return true and stops
> iterating through.
>
> Example:
>
> const stringOne = "Matheus";const manyStrings = ['robert', 'lucas', 
> 'matheus'];stringOne.ignoreCase('', manyStrings) // true;
>
> 2. Response
>
> The function is going to return true or false. The result depends on
> equality between chosen strings.
> 3. How does
> it work?
>
> The function converts all of the strings, which the developer chose to the
> lower case. After performing the previous operation, it compares all of
> them. If at least one, equals the provided parent string, then the function
> returns true.
>
>
> You can the proposal on my GitHub:
> https://github.com/robertjwozniak/ignoreCase
>
>
> --
> Regards,
> Robert Wozniak
> ___
> 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


Array#flat is coming to ES; would you like like some sugar with that?

2018-06-21 Thread Michael Luder-Rosefield
Apologies 'if' this is a terrible idea, but since I have just encountered a
situation where this sugar would actually be useful I'm absolutely going to
suggest it.

Extend the ... syntax to allow for flattening deconstructed arrays.
_Literally_ extend it:

array === ...(array.flat()) // i.e. depth 1
.array === ...(array.flat(0)) // unlimited depth
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Phase-Invariant Einno Soliton Templates

2018-05-20 Thread Michael Luder-Rosefield
I've been suspecting along similar lines, but was reticent to make any
outright accusations.

On Mon, 21 May 2018, 00:41 Sanford Whiteman, <
swhitemanlistens-softw...@figureone.com> wrote:

> > I personally would prefer that these proposals are specified in terms
> > of *what's actually being proposed*
>
> I think what's actually being proposed is that we fall for a troll.
>
> Possibly an academic troll who will later ridicule its victims, viz.
> the Social Text scandal (https://en.wikipedia.org/wiki/Sokal_affair).
>
> A pity, since I love receiving this list to graze over your and
> others' intelligent and serious comments on the future of the
> language.
>
> —— Sandy
>
> ___
> 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: Phase-Invariant Einno Soliton Templates

2018-05-20 Thread Michael Luder-Rosefield
At this point I fully expect Abdul to describe the Norse, Greek and Hindu
pantheons in terms of turbulence physics and give a few pseudocode JS
snippets indicating that they can also be used to handle REST requests.
And all in 3 short sentences.

On Sun, 20 May 2018 at 02:49 kdex  wrote:

> To me, what you're actually seeking to discuss looks less related to
> physics
> and more like an extension to ECMAScript's `import` syntax.
>
> Would you please describe it a little more? A good conversation starter,
> preferably without any domain-specific context (i.e. physics), would
> entail:
>
> - the set of generalized (= non-domain-specific) problems it solves
> - the desugaring you have in mind
> - how a solution to your problem might look without introducing new syntax
> (ideally also the reasoning why you consider new syntax to be justified)
>
> On Sunday, May 20, 2018 3:12:34 AM CEST Abdul Shabazz wrote:
> > Of the five (5) known forms of matter:
> >
> >
> >
> >1. Solid (well-structured arrangement of tightly bound atoms, found in
> >ice)
> >2. Liquid (unstructured arrangement of tightly-bound atoms)
> >3. Gas (loose arrangement of atoms)
> >4. Plasma (Properties of liquid, electricity, and magnetism found @
> the
> >core of our sun)
> >5. Bose-Einstein condensates (Properties of gas and phase-invariant
> >liquid, ie. a superfluid)
> >
> >
> > ...Another sixth (6th) form of matter was uncovered six weeks ago at UT
> > Dallas: the "Superfluid Quasicrystal" -- which has the properties of both
> > quasicrystals and superfluids, wherein Quasi crystals have atoms that are
> > arranged in a highly ordered, periodic pattern that is unchanged when you
> > rotate or repeat it, eg. in table salts)
> >
> >
> > This sixth (6th) form of matter exhibits properties of a Soliton: A
> Soliton
> > or Einno Soliton Tsunami is a gathering phase-invariant wave that
> maintains
> > its shape and velocity as it travels through any phase of matter.
> >
> >
> > An example implementation perhaps in javascript would be:
> >
> >
> > // file1.jsol
> >
> >
> > ${0} = (lhs,rhs) => { return (lhs ${1} rhs) }
> >
> >
> > // file2.js
> >
> >
> > import file1.["add",Symbol.operator.addition] as bar
> >
> > let foo = bar.add(4,2) // returns 6
> >
> >
> > // file3.js
> >
> >
> > import file1.["mul",Symbol.operator.multiplication] as bar
> >
> > let foo = bar.mul(4,2) // returns
> 8___
> 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: Proposal: Pilot-Wave -based execution flow

2018-05-12 Thread Michael Luder-Rosefield
can I be the first to say: what


On Sat, 12 May 2018, 16:31 Abdul Shabazz,  wrote:

> A velocity vector can also be added to detect the presence of malware,
> which in turn can effect the mass. If the mass at any point is changed,
> then the pipeline is dropped.
> --
> Abdul S.
> ___
> 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: Implicit variables

2018-05-09 Thread Michael Luder-Rosefield
Could you suggest an example?

On Wed, 9 May 2018 at 14:50 Abdul Shabazz  wrote:

> Allow javascript to facilitate implicit variables by way of an advanced
> built-in reasoning engine or theorem prover. Thereby, allowing javascript
> to become a more powerful semantics driven language whereby the software
> developer need not always be bothered with implementation.
> --
> Abdul S.
> ___
> 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: Accessing (n)th key from an object

2018-04-24 Thread Michael Luder-Rosefield
I've found myself using that pattern, actually. Say you have multiple
variables and want to pass one of them on to a function, which wants to
know the value (of course) of that variable but also some kind of name to
know which one was passed on.

The easiest way to do this in one pass at the stage you pass it on is for
the variable name to match the one needed later, and send it to the
function as the object `{ whateverName }`.

It does require, alas, more fiddling about to get the key/value pair from
the object after.

On Tue, 24 Apr 2018 at 15:19 T.J. Crowder 
wrote:

> On Tue, Apr 24, 2018 at 2:54 PM, somonek
>  wrote:
> > ...
> >
> > could
> > myObject[in 0] === 'one' // true
>
> What's the use case? Relying on the order of the properties in the object
> is almost always a bad idea (although if I read the current spec correctly,
> `Object.keys` is no longer exempt from order as it once was). The only time
> I've seen this done that seemed reasonable was when the object was known to
> have a single own enumerable property but that property's name was unknown
> (which was, in itself, an X/Y problem -- the real problem was why that name
> was unknown/varied at runtime).
>
> -- T.J. Crowder
> ___
> 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: WHO CAN HELP ME TO UNSUBSCRIBE THIS EMAIL

2018-04-20 Thread Michael Luder-Rosefield
Can anyone put together a strawman proposal for unsubscribing from this
email?

I suggest using `!@` as the operator.

On Fri, 20 Apr 2018 at 04:59 Felipe Nascimento de Moura <
felipenmo...@gmail.com> wrote:

> well, access the link:
> https://mail.mozilla.org/listinfo/es-discuss
>
> then look for the part that talks about "unsubscrib"
>
> is that what you needed?
>
> [ ]s
>
> *--*
>
> *Felipe N. Moura*
> Web Developer, Google Developer Expert
> , Founder of
> BrazilJS  and Nasc .
>
> Website:  http://felipenmoura.com / http://nasc.io/
> Twitter:@felipenmoura 
> Facebook: http://fb.com/felipenmoura
> LinkedIn: http://goo.gl/qGmq
> -
> *Changing  the  world*  is the least I expect from  myself!
>
> On Thu, Apr 19, 2018 at 11:24 PM, Dylan  wrote:
>
>>
>> ___
>> 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


Allow arrow functions with conventional 'function' declarations

2018-03-29 Thread Michael Luder-Rosefield
You're probably asking what on Earth the point of this is, and I'll tell
you: _hoisting_.

My preferred ES5 code style was always to declare functions after their use:

```
doSomething1();
doSomething2();

function doSomething1 () {
  // ...
}

function doSomething2 () {
  // ...
}

It keeps things uncluttered and readable: you don't have to read through
random functions before they are used, and have to work out what they're
doing there.

If you're able to make use of ES6 arrow functions declared with
`const`/`let`, though, you would have to declare them before use. This
obviously goes against my preferred style, and can also result in
inconsistent placing of function declarations when mixed with conventional
functions.

My proposal is simple: after the initial `function name (params)`, allow
the following forms:
1. { // body code }
2. => { // body code }
3. => // expression ;

1. is of course the current form
2. is similar, except it's a block body arrow function (all the usual arrow
function differences apply; this binding, cannot be used with 'new', no
'arguments', no 'super'...)
3. allows for concise body arrow functions - semi-colon at end.

Example:

```
// with proposal
doSomething1();
doSomething2()
  .then(doSomething3);

function doSomething1 () {
 // conventional function
}

function doSomething2 () => {
 // block body arrow function
}

function doSomething3 (value) => value ? foo(value) : bar();

// without proposal
const doSomething2 = () => {
  // block body arrow function
  };
doSomething3 = value => value ? foo(value) : bar();

doSomething1();
doSomething2()
  .then(doSomething3);

function doSomething1 () {
 // conventional function
}
```
As you can see, the latter code is just... messy and unpleasant.

I don't think there's any potential issues in regards to interpreting
syntax (it just requires a simple check for an arrow after the parameters),
nor with readability. Async We would definitely need to clarify behaviour
with `async` and generator functions, though.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: if variable initialization

2018-03-22 Thread Michael Luder-Rosefield
That strikes me as territory the 'do expression' proposal
https://github.com/tc39/proposal-do-expressions is more fitted for:

const x = do { if (c) expr; else { ... } };

What I'd like for this proposal is something that works consistently and
obviously for all blocks with a parenthesised element to them. When they're
formally separated by semi-colons, as in `for (a;b;c)`, each of `a,b,c`
acts as an expression. Why not allow any of those expressions to be
replaced by a statement block that acts like a do expression, each of
which's scope is nested under the previous one and are available to the
following block?

That didn't come out very clearly, so let's try with an example:

  for ({
  let x = 1, y = 2;
  console.log("I'll be printed every loop!");
}; {
  let s = 'some string';
  if (y%7 === 0) x === y;
  else x < 1000;
}; {
  let s = 'some other string';
  x+=1;
  if (y%3 === 0) y += 2;
  else y += 1;
}) {
  // whatever code here
  // local scope hierarchy is
  //   {
  // x,
  //y,
  //__SCOPE__: {
  //  s: 'some string',
  //  __SCOPE__: {
  //s: 'some other string'
  //  }
  //}
  //  }
}

I'm just using some random logic in the blocks to illustrate the point: all
the variables declared in the blocks are accessible in the for block, but
the 'some string' `s` is masked by the 'some other string' `s` in the child
scope. The termination condition in the second block can vary each loop, as
can the iteration operation in the last block, and is simply the last value
in the block as-per do expressions.

On Thu, 22 Mar 2018 at 15:44 Mike Samuel  wrote:

> On Thu, Mar 22, 2018 at 3:50 AM, Isiah Meadows 
> wrote:
>
>>
>> I do have one other related thing I'd like to see: add a `let foo =
>> expr() else { ... }` variant, with a line terminator restriction
>> before the `else` so it can't be confused with an `else` within an
>> `if`.
>>
>
> Making it a restricted production would solve the grammatical ambiguity
> for existing code, but maybe in an errorprone way for future code:
>
> if (c) let foo = expr() else { ... } // else attaches to let
> if (c) let foo = expr(); else { ... } // else attaches to if
>
>
> Would the semantics differ from
>
>let foo = expr() || ({} => { ... })()
>
> ?
>
>
>
>
>
>>
>> -
>>
>> Isiah Meadows
>> m...@isiahmeadows.com
>>
>> Looking for web consulting? Or a new website?
>> Send me an email and we can get started.
>> www.isiahmeadows.com
>>
>>
>> On Thu, Mar 22, 2018 at 3:21 AM, Rodrigo  wrote:
>> > Not just let-scopes, but the introduction of `async/await` also
>> > welcomes the introduction of if-scoped variables.
>> >
>> > if (const data = await collection.find({}).toArray(); data.length >
>> 10)
>> > {
>> > console.log(data);
>> > } else if (data.length > 0) {
>> > console.log(data);
>> > } else {
>> > console.log(data);
>> > }
>> >
>> > And, as mentioned by @jerry, this can be extended to `switch` and
>> > `while`. Golang has `switch(;)` initialization too afaik.
>> >
>> > switch( const today = new Date(); today.getDay() ) {
>> >  case 0:
>> > console.log( "Don't work on %s", today.toString() );
>> > break;
>> > }
>> >
>> > `while` would be a bit unnecessary, due to the fact that it can be
>> > replicated with `for( ; ; )`, but could be
>> > available for consistency with `if` and `switch`.
>> >
>> > El mié., 21 mar. 2018 19:47, Mike Samuel 
>> escribió:
>> >>
>> >>
>> >>
>> >> On Wed, Mar 21, 2018 at 1:27 PM, Sebastian Malton <
>> sebast...@malton.name>
>> >> wrote:
>> >>>
>> >>> Because block-level scoping is a very good way to avoid certain bugs
>> and
>> >>> is easier to reason about. Especially when considering project
>> successors.
>> >>
>> >>
>> >> +1.  function-scoped variables in loop bodies caused tons of bugs
>> before
>> >> let-scoped variables and were a main motivating case.
>> >>
>> >> var i;
>> >> for (i = 0; i < arr.length; ++i) {
>> >>   f(function () { /* Do something with */ arr[i]; });
>> >> }
>> >>
>> >> vs
>> >>
>> >> for (let i = 0; i < arr.length; ++i) {
>> >>   f(function () { /* Do something with */ arr[i]; });
>> >> }
>> >>
>> >> Yes, linters got pretty good at finding uses of closed-over variables
>> >> modified in a loop, but the workarounds were not ideal.
>> >>
>> >> var i;
>> >> for (i = 0; i < arr.length; ++i) {
>> >>   f(function (i) { return function () { /* Do something with */
>> arr[i]; }
>> >> }(i));
>> >> }
>> >>
>> >> Block scoping is just better for code that uses loops, variables, and
>> >> function expressions.
>> >>
>> >> ___
>> >> es-discuss mailing list
>> >> es-discuss@mozilla.org
>> >> https://mail.mozilla.org/listinfo/es-discuss
>> >
>> >
>> > 

Re: Promise finally

2018-02-23 Thread Michael Luder-Rosefield
Whenever you chain a promise with a then/finally, you're basically letting
the runtime look at the callbacks at some arbitrary point in the future,
no? So despite being written in a defined order, they will be run in
whatever order eventuates.

On Fri, 23 Feb 2018 at 14:24 Raul-Sebastian Mihăilă 
wrote:

> The order is deterministic, as specified, I just don't think it's the
> right order. I don't have a concrete example with finally, but if I were to
> imagine one, say you're writing some tests with jest and you want to make
> some checks in the then callbacks. In order for those checks to be executed
> in good time, you must return a promise from the test callback. If you have
> more promises you have to do a Promise.all in order to make sure that you
> wait for all the promises. If you are able to determine the order in which
> the promises are settled, you can return the one that is settled the last.
> This is perhaps not a convincing example, but if this didn't matter why is
> the order specified?
>
> On Fri, Feb 23, 2018 at 3:59 PM, Viktor Kronvall <
> viktor.kronv...@gmail.com> wrote:
>
>> Since these two Promises aren't chained to one another I wouldn't expect
>> any specific
>> deterministic ordering between the `console.log` statements. Are you
>> suggesting that
>> such a deterministic ordering should be imposed by using micro tasks or
>> what are you
>> proposing here exactly?
>>
>> In other words, why exactly do you expect the result to always be
>> printing 1 before
>> printing 2?
>>
>> 2018年2月23日(金) 19:21 Raul-Sebastian Mihăilă :
>>
>>> I find it weird that
>>>
>>> ```js
>>> Promise.resolve().finally(() => {}).then(() => { console.log(1); });
>>> Promise.resolve().then(() => {}).then(() => { console.log(2); });
>>> ```
>>>
>>> prints 2 and then 1. It would have been possible to spec it in such a
>>> way that it would have printed 1 and 2.
>>>
>>> On the other hand
>>>
>>> ```js
>>> Promise.resolve().finally().then(() => { console.log(1); });
>>> Promise.resolve().then().then(() => { console.log(2); });
>>> ```
>>>
>>> prints 1 and then 2.
>>> ___
>>> 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: try/catch/else

2018-02-08 Thread Michael Luder-Rosefield
Well, since promise.then(/**blah**/).catch(/**blah**/) is already a thing,
why not stick with that?

try {
 // blah
} then(val) {
  // blah
} catch {
 // blah
} finally {
 // blah
}

I added `val` to the then since we might want to pass something from `try`
to it, just as promises do. Best way to do that might be for `try` to act
as an expression block and implicitly return the last thing in it.

On Thu, 8 Feb 2018 at 14:50 Alan Plum  wrote:

> Hi everyone,
>
> I'm hoping this is the right medium to ask this but I would like to
> propose a language feature called try/catch/else.
>
> Conditional try/catch seems to be all the rage right now but in many cases
> the problem it really wants to solve seems to be code like the following:
>
> try {
>   const suggestions = await fetchSuggestions();
>   showSuggestions(suggestions);
> } catch (e) {
>   alert('Failed to load suggestions');
>   // Oops, we also swallow errors from showSuggestions
> }
> // now do something else
>
> Having a more fine-grained catch wouldn't necessarily help here because
> both functions might throw the same kind of error but what we're really
> interested in is discerning the *source* of the error. So instead some
> people resort to something like this:
>
> let suggestions;
> try {
>   suggestions = await fetchSuggestions();
> } catch (e) {
>   alert('Failed to load suggestions');
>   return;
> }
> showSuggestions(suggestions);
> // now do something else - unless we failed to load
>
> Note how we're forced to add a return to explicitly abort the control
> flow. Unlike the change from const to let this isn't something an IDE would
> point out while refactoring, so this actually introduces potential for
> bugs. If we don't actually want to bail out completely this often leads to
> noisy status booleans (e.g. didNotThrow) or error-prone checks (e.g.
> !suggestions is a bug if the async function really didn't return
> anything).
>
> I'm not sure about other languages but Python has a solution for this by
> adding an else clause:
>
> let suggestions;
> try {
>   suggestions = await fetchSuggestions();
> } catch (e) {
>   alert('Failed to load suggestions');
> } else {
>   showSuggestions(suggestions);
> }
> // now do something else
>
> The semantics are pretty straightforward: if the try block did not throw,
> the else block is executed next (before the finally block if any). If the
> try block does throw, the else block is ignored (like a conditional catch
> that doesn't match).
>
> I realise there is some ambiguity in using the else keyword for this
> (though I can't think of a meaningful opposite of "catch" either). There is
> also some overlap with conditional try/catch but I think this language
> feature is useful even if conditional try/catch exists.
>
>
> Cheers,
>
> Alan Plum
> ___
> 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