Re: Destructuring by

2021-03-03 Thread Augusto Moura
> that's basically the entirety of the syntax sugar proposals since ES2015,
right?

Definitely no, but talking about the syntax additions since ES2015, they
are in one or more of the categories below:
- avoid known footguns in the language (arrow functions and lexical this,
classes and prototype, let/const and block scoping, nullish coalescing
operator, etc.)
- syntax sugars with strong community feedback AND battle proven prior art
(classes, destructuring, string templates, rest, spread and default
values, async/await, etc.)
- introducing or specifying new mechanisms that didn't exist before in ecma
(modules, classes, varargs, etc.)

> also proxy and globalThis are *really* unrelated to this

Proxy and globalThis (and the `with` statement for that matter), are
mechanisms of value indirection aside from the "classic" instance properties

>  while leaking objects all over down the pipe is my major concern,
something this proposal avoids, as no code will have a reference to the
entirety of the source object, they'll deal with a known property name
passed by reference, incapable of changing anything else in the source
object ... so it's rather a signal, than a convention.

How will you prevent the passing of the object down the pipe? You mean the
reference variable being passed to another function and setting the prop
into the source object?
```js
function foo(source) {
  let {  } = source;
  value = 'foo';
}

function second(source) {
  // You still need to pass the object forward right?
  foo(source)

  // Or the proposal is something like this
  let {  } = source;
  foo(value);
  // and then if foo sets the value argument it should reflect in source
}
```

Also the usual way of preventing the "passing the full object down" problem
is restricting the contract with other functions using a wrapper/proxy, a
well defined more specific interface or in the readonly case just omitting
the other properties

```ts
// Wrapper way
class Nameable {
  constructor(instance) { this.#obj = instance }
  get name() { return this.#obj.name }
  set name(newName) { this.#obj.name = newName }
}

function printName(nameable) {
  console.log(nameable.name)
  nameable.name += ' [printed]'
}
function foo(source) {
  printName(new Nameable(source))
}
foo({ name: 'foo', type: 'pojo' })

// Well defined contract way (using Typescript, but you could rely on duck
typing if you trust the good manners of the developers)
interface Nameable {
  name: string;
}
interface Pojo extends Nameable {
  type: string;
}

function printName(nameable: Nameable) {
  console.log(nameable.name)
  nameable.name += ' [printed]'
  // the function still can access the type field by ignoring the typing,
but at this point this is the least scary thing a developer in a app
}
function foo(source: Pojo) {
  printName(source)
}

// Omit and readonly way
function printName(nameable) { /* ... */ }
function foo(source) {
  printName(pick(source, ['name']))
}
```
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Destructuring by

2021-03-03 Thread Augusto Moura
> ```js
> function stuff(source, extra) {
>   const {value, method} = source;
>
>   if (condition)
> method.call(source);
>
>   if (value === extra)
> source.value = 'no more';
> }
> ```

I mean, in this case you can skip destructuring altogether, having a one
way and way only of value indirection is a Pretty Good Thing™ (even though
we already have proxys, globalThis and other indirection shenanigans), I
never felt annoyed of just using `source.value` or `source.method()`
instead of `value` and `method()`, again the proposal is just a debatable
syntax sugar for something we already can do. I wonder if we could ever do
the reference thingy in user-land with variable level decorators, if it
ever gets discussed again in the meetings. Would be still kinda fishy to
propose and implement
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Destructuring by

2021-03-03 Thread Augusto Moura
I don't know, the by reference destructuring seems a bit too much magical,
a scoped variable that sets to a property to a object just sounds like the
old `with` statement but reduced and more explicit, given is just a sugar
and currently the problem is not a great of a pain point I would be very
picky a proposal like that, any prior art in other languages?

Also, from a grammar/vendor implementation standpoint I would imagine the
definition of a by reference variable bind would be kinda fishy, I might be
wrong though

Em ter., 2 de mar. de 2021 às 21:03, Claudia Meadows <
cont...@isiahmeadows.com> escreveu:

> I would like to see this happen, though I'd like to see it integrated with
> reified refs. (I know there's a proposal laying around somewhere drafted up
> by a current or former TC39 person, but I can't find it.)
>
> -
>
> Claudia Meadows
> cont...@isiahmeadows.com
>
>
> On Tue, Mar 2, 2021 at 11:05 AM Andrea Giammarchi <
> andrea.giammar...@gmail.com> wrote:
>
>> Another one (cit. DJ Khaled)
>>
>> has "by reference" ever been considered as "yet another JS syntax" ???
>>
>> let object = {value: 1};
>> let {} = object;
>> value = 2;
>>
>> object.value; // 2
>>
>> allowed everywhere destructuring is possible, throwing for frozen
>> properties ... is this just meh? .. .'cause I think, specially for function
>> signatures declaration, it might make a difference, when mutability matters.
>>
>> Cheers 
>>
>> P.S. for transpilers this would simply carry, repeatedly, the initial
>> reference.prop around, instead of using just prop.
>>
>> ___
>> 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
>


-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Are ES6 modules in browsers going to get loaded level-by-level?

2020-10-22 Thread Augusto Moura
We could wirte a simpler parser just for the imports subset, given the
simpler isolated grammar I don't think is that hard with parser
combinators. Maybe it's a cool idea for a npm library that just points out
the dependencies of a single file and then recursively scan the rest. From
that is just hook some cache system to a node server and voi'la

I migh try it as a weekend toy project

Em qui, 22 de out de 2020 23:26, J Decker  escreveu:

>
>
> On Thu, Oct 22, 2020 at 2:23 PM #!/JoePea  wrote:
>
>> >  It's caused me some headaches especially when dealing with
>> inheritance/extends and in workers.
>>
>> Like, extending from a `Module` object?
>>
>> > Maybe someday we'll have a `modules` collection we can interrogate.
>>
>> That may be nice, to query which modules have already been imported, etc.
>>
>> It would also be great if we could unload modules.
>>
>> ---
>>
>> Skypack is making news rounds as an ESM server: http://skypack.dev/
>>
>> It says it supports HTTP/2 and HTTP/3. But it isn't open source.
>>
>> Seems that there isn't any open source solution (otherwise I'm sure
>> people would be using that over bundling if it works out better, at
>> least alternatives to skypack would exist, f.e. well-know projects
>> like React, Angular, Vue, Svelte, etc, could all have their own ES
>> Module servers if it was viable).
>>
>> Seems that there hasn't been any free/open project to prove viability
>> yet, and the existing ones are closed source.
>>
>> Seems that even http://jspm.dev is closed source.
>>
>> Looks like at this point in time people are aiming to make money from
>> ESM servers, and there's no viable open source ESM server solution.
>>
>> Seems like it wouldn't be a LOT of work to take Acorn (
> https://www.npmjs.com/package/acorn ) and http server (
> https://www.npmjs.com/package/http ) and parse the pages loaded if
> (*.[cm]+js) (something)
>
> Though my observation is that when the browser gets the first page, async
> requests go out for more content even before it's actually interpreted/run
> the script; and the requests are streamed over one or more http(s)
> connections.  this screenshot https://pasteboard.co/JwUnbAD.png  of this
> demo http://d3x0r.github.io/Voxelarium.js/  shows the network load time;
> recently updated to imports and non-built scripts...though I do see a
> gap where the html script loading ends and the imports in the scripts
> actually go... but that could also be the pause setting up the opengl
> surface... it's about 50ms.
>
> since 'import' is itself async I sort of expected a lot of overlap in the
> requests; there's only a single network wire, so there's not a LOT to be
> gained parallelizing things.
>
> If there was even some sort of manifest could make a background service
> worker (which itself doesn't support import
> https://bugs.chromium.org/p/chromium/issues/detail?id=680046 ) which can
> behave like a offline storage/cache so the server can dump requests to the
> client before it knows to ask for them... and then it doesn't have to ask
> the server for anything  at all later even; which sort of de-emphasizes all
> the work put into the server in the first place :)
>
> J
>
> #!/JoePea
>>
>> On Sun, Oct 18, 2020 at 8:50 AM Randy Buchholz 
>> wrote:
>> >
>> > Right, it's basically just doing what an import aware server might do
>> and the type-tree is a hierarchal version of the scope imports. The rest is
>> just extra stuff. Probably the biggest difference though is that it lets me
>> isolate prototypes. From what I gather it seems that import stores a live
>> "ghosted" version of the prototype that it checks before making additional
>> requests for the item. The scope basically gets a reference to this
>> prototype. If you do things like add a property with reflect in one scope
>> that property shows up everywhere. And since it modified the "ghost" it
>> persists after the scope goes away. It's caused me some headaches
>> especially when dealing with inheritance/extends and in workers.
>> >
>> > Yeah, inspecting is in issue. I haven't found a way to inspect modules
>> to see what they have in them. They're a strange beast. You can see their
>> scope in the debugger and they look like an ES Object or IDL interface, but
>> I don't know how to get a reference to them in code. But, they're new, so
>> we'll see where they go. Maybe someday we'll have a `modules` collection we
>> can interrogate.
>> >
>> > -Original Message-
>> > From: #!/JoePea 
>> > Sent: Saturday, October 17, 2020 10:35 PM
>> > To: Randy Buchholz 
>> > Cc: es-discuss@mozilla.org
>> > Subject: Re: Are ES6 modules in browsers going to get loaded
>> level-by-level?
>> >
>> > That's neat, but it seems like the same work that a server would have
>> to do with actual ES Module imports, right? And the "type tree"
>> > equivalent is the modules that the JS engine stores as a map from
>> import identifier to module scope instance. It seems that in the end, the
>> `PUSH` approach should work 

Re: [PROPOSAL] Provide a way to enforce integrity check on module imports

2020-08-01 Thread Augusto Moura
Maybe a convention between hosts to prefix an import with an integrity
check?
``` js
import foo from 'sha1sum:ef70d15a0700d2108e0df27dde750f5c682b4697!./foo.js';
```
It looks kinda of dirty, but the specification allows it (aside from the
colon character that is forbidden right now)

This types of urls remember me of a past time when bundlers used to have
loaders prefixes, like `import style from 'css-loader:./styles.css'`

Em sáb., 1 de ago. de 2020 às 14:33, Bergi  escreveu:

> Hi,
>
> > The problem with inlining the integrity into every import site is that
> this
> > is naturally incompatible with import maps.
>
> I don't see a problem with that. When using import maps, you should be
> able to specifiy the integrity check in the import map, not needing it
> in the module itself.
> When not using import maps, specifying the integrity in the importing
> module itself seems to give the best developer experience, following the
> rationale of
> https://github.com/tc39/proposal-import-assertions#why-not-out-of-band.
> When using it in *both* places, then of course both integrity checks
> would need to match, and an import map would be prevented from swapping
> out the module under your hands.
>
> kind regards,
>  Bergi
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>


-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Object.safeAssign

2020-05-08 Thread Augusto Moura
The real risk are the exploits that are not made public

In my opinion __proto__ as a whole should be the one to be dropped,
unfortunately this is not happening in the near future. My hope is that one
day, years after now, the usage is so low that it can be removed from the
language. That would solve a big list of exploits. I don't see that much of
a problem with setting constructor or prototype though. Maybe we should
promote a more aggressive deprecation? Discuss with browsers to log
warnings and make more explicit in documentation the hazards with counting
on it. Anyway maybe the problem are not serious enough to get that
attention.

Em sex., 1 de mai. de 2020 às 13:31, Mike Sherov 
escreveu:

> So, I've firmed up my understanding here. The goal of a safeAssign would
> not be to prevent all prototype pollution, which seems impossible to solve
> generically at a library level. But rather to prevent the assignment
> specifically of `__proto__`, `constructor`, and `prototype` properties of
> the target. This mitigates a specific, well understood vulnerability:
> manipulating a prototype with a "src" object that can surive a
> JSON.parse(JSON.stringify(src)) roundtrip.
>
> > Can you explain or support your assertion of "increased prevalence"?
>
> I should probably have said visibility, not prevalence. MITRE shows 31
> CVEs for prototype pollution:
> https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=prototype+pollution including
> another new one in lodash today. https://snyk.io/vuln/npm:lodash:20180130
>
> On Fri, May 1, 2020 at 12:13 PM Isiah Meadows 
> wrote:
>
>> Missed the list. Also, it apparently does trigger setters. Crossed it up
>> with spread properties (which don't).
>>
>> On Fri, May 1, 2020 at 06:28 Isiah Meadows 
>> wrote:
>>
>>> I thought `Object.assign`already used the `Object.keys` +
>>> `Object.defineProperty` algorithms under the hood and thus were immune to
>>> this. Am I misremembering or misunderstanding?
>>>
>>> On Fri, May 1, 2020 at 05:51 Mike Sherov  wrote:
>>>
 Given the increased prevalence of prototype pollution vulnerabilities
 in many popular javascript libraries, is it time to reconsider the fact
 that Object.assign allows for prototype pollution by default?

 I see two options:
 1. Change Object.assign to disallow PP by default. Look at real world
 usages and see what would break if prototype pollution was disabled? Almost
 certainly this is not a viable option, but wanted to raise it here just in
 case there was appetite to do so.
 2. Introduce something like Object.safeAssign (bikeshedding aside),
 that is the same as Object.assign except is safe from prototype pollution.

 The reason I think this is important is that the common advice of
 freezing Object.prototype is something only the end user can do, and not
 something a library can do.

 Yes, a library can also know to do its own PP fixes, but having a
 reified way to avoid PP allows us to have a secure-by-default method in the
 language.

 Thoughts?

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

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


-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Double wildcard "re-exports"... off-limits forever?

2020-02-14 Thread Augusto Moura
If I understand it correctly, I had a similar problem with generated apis
from OpenApi, two apis have a error definition with the name ApiError, i
want to reexport all classes (a lot of model definitions) from both apis.
The problem is that using `export * from 'api-a'; export * from 'api-b';`
raises a error that ApiError is a duplicated name. So I have 2 options, or
I reexport all definitions from the apis explicitly (hundreds of `export {
Foo } from 'api-b'`) just to rename the ApiError to ApiAError at then end
or I don't rexport then together at all (splitting the reexports in 2 files
and having the dev to import the necessary models from the different files).

If we could have a rest-operator like construct for imports the problem
would be solved, something like:
```js
// api-a.js
export { Foo, ApiError };

// api-b.js
export { Bar, ApiError };

// apis.js
export { ApiError as ApiAError, * } from './api-a.js'; // exporting Foo and
ApiAError
export { ApiError as ApiBError, * } from './api-b.js'; // exporting Bar and
ApiBError

// other ideas for syntax
export { ApiError as  ApiAError }, * from './api-a.js'; // similiar to
default and named imports
export { ApiError as  ApiAError, ... } from './api-a.js'; // similar to
spread syntax
export { ApiError as  ApiAError, ...* } from './api-a.js'; // mix from
spread syntax and wild card imports
// this last is one is the one I like the most, because both wildcards and
spread are already familiar in the language, and it reads like "import the
rest and rexport as it is"
```

Em sex., 14 de fev. de 2020 às 01:02, Ben Wiley 
escreveu:

> Apologies if this has already been talked about at length at some point. I
> was unable to find much in the way of relevant discussions.
>
> I found a compelling use case for something which seems to be off-limits
> in the JavaScript language, that is wildcard re-exporting where the same
> export name appears in multiple of the export-forwarded imports.
>
> e.g.
> ```
> // a.js
> export const a = 1;
>
> // b.js
> export const b = 2;
>
> // c.js
> export * from './a.js';
> export * from './b.js';
> ```
>
> The ideal use case would be shipping an "override library" that ships all
> the default exports of an upstream library, except it replaces some of them
> with its own overrides. The object-oriented folks might think of it like a
> derived class. This can of course be accomplished alternatively by
> exporting an object which merges all the named exports from each library,
> but the major disadvantage I see is that we would no longer have access to
> tree-shaking, since that object contains *all* of the exports. For a really
> big upstream library, that could make a large difference in kilobytes
> shipped to the browser. So preserving the named exports is desirable.
>
> The protections against double-re-exporting vary. In Chrome and Firefox,
> there are no runtime errors but the duplicated exports will be stripped and
> unavailable. If you try Babel or Typescript, the compiler will throw an
> error.
>
> I understand *not* protecting against this could lead to very weird
> debugging situations for unwitting users who didn't realize their wanted
> import was being overwritten, however I'd love if there were a way to say
> "I know what I'm doing, don't stop me." As far as I can immediately tell
> nothing about ES imports would prevent the compiler from being able to know
> the order of precedence for overridden exports, and the "ambiguity" would
> be mainly from the perspective of an unwitting user. I recognize that
> import trees may be processed in parallel, however since code execution is
> delayed until the import tree is complete I would think we could resolve
> any ambiguities by that time. However it's possible I missed something -
> maybe there's a case related to circular imports which ruins this?
>
> Anyway, I wrote up some more detailed thoughts on this problem, and some
> demo code, here:
> https://github.com/benwiley4000/wildcard-export-override-example
>
> Ben
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>


-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Array.prototype.toggle

2020-02-07 Thread Augusto Moura
To me this is more a use case for using Set instead of arrays, the support
is already great and it can be polyfilled. Set is the right data structure
to verify if some element is or is not in a collection

Em sex., 7 de fev. de 2020 às 08:49, manuelbarzi 
escreveu:

> just a proposal to provide this functionality into array, allowing to add
> / remove items in a toggling mechanism shortcut, avoiding the need to do
> traversing to locate the indexes and remove them next (i.e. by means of a
> polyfill or any other approach).
>
> ```js
> [1, 2, 3, 2, 1].toggle(1) // mutates the original array removing 1,
> resulting in [2, 3, 2]
> ```
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>


-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Awaiting block expression

2019-06-21 Thread Augusto Moura
Actually... You are proposing a `await` in a block, and a implicit
await in all Promile-like expressions (or every expression) in the
block, that's a totally different beast

I don't think the implicit await part can be easily implemented
neither is a good idea, the code flow can get really confusing,
imagine the following:

``` js
const foo = await {
  const bar = {
then(callback) {
},
  };
  return bar;
}
```

What should be the result? Translating your proposal to already valid
code it should be:

``` js
const foo = await (async function() {
  const bar = await {
then(callback) {
},
  };
  return bar;
}());
```

Foo will never be resolved, because the awaited `bar` object never
calls the callback argument, and the whole block stagnates waiting for
something that will never happen

Em sex, 21 de jun de 2019 às 10:40, Augusto Moura
 escreveu:
>
> The do expressions proposal[1] had some discussions about having a
> `async` variant[2] you should give it a look
> Is the same concept you are proposing
>
> [1]: https://github.com/tc39/proposal-do-expressions
> [2]: https://github.com/tc39/proposal-do-expressions/issues/4
>
> Em sex, 21 de jun de 2019 às 03:42, Tobias Buschor
>  escreveu:
> >
> > As there are more and more async apis, i would like to have a block, where 
> > all promises within automaticly are awaited:
> >
> > Proposal:
> >
> > const image = await {
> > const user = fetch('/user/'+id).json();
> > fetch('/image/'+user.image).json();
> > }
> >
> > ___
> > es-discuss mailing list
> > es-discuss@mozilla.org
> > https://mail.mozilla.org/listinfo/es-discuss
>
>
>
> --
> Atenciosamente,
>
> Augusto Borges de Moura



-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Awaiting block expression

2019-06-21 Thread Augusto Moura
The do expressions proposal[1] had some discussions about having a
`async` variant[2] you should give it a look
Is the same concept you are proposing

[1]: https://github.com/tc39/proposal-do-expressions
[2]: https://github.com/tc39/proposal-do-expressions/issues/4

Em sex, 21 de jun de 2019 às 03:42, Tobias Buschor
 escreveu:
>
> As there are more and more async apis, i would like to have a block, where 
> all promises within automaticly are awaited:
>
> Proposal:
>
> const image = await {
> const user = fetch('/user/'+id).json();
> fetch('/image/'+user.image).json();
> }
>
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Re: What do you think about a C# 6 like nameof() expression for

2019-06-14 Thread Augusto Moura
Fri, 14 jun 2019 - 18:29, Jordan Harband  wrote:
>
> `nameof whatever` → `Object.keys({ whatever })[0]`, but I'm a bit confused 
> why it'd be better to type `nameof foo` in code, rather than `'foo'` - if you 
> change `foo` to `bar`, you have to change both of them anyways.
>

Exactly, if you already have the name of the property beforehand in
design time why not write it as a string literal

Again, the only justifiable use case is refactoring tools, but even
today that can be arranged with static code analysis

You can safe guard a string literal to be a property of a type in
Typescript with a bit of handwork
``` ts
interface Options {
  userName?: string;
}

// If you change the property in the interface without changing here, Typescript
// will raise a error informing that 'userName' is not a valid key of Options
const userNameKey: keyof Options = 'userName';

if (options.userName === undefined) {
  throw new ParamNullError(userNameKey);
}
```

-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Re: What do you think about a C# 6 like nameof() expression for

2019-06-14 Thread Augusto Moura
Can you list the benefits of having this operators? Maybe with example use cases

If I understand it correctly, the operator fits better in compiled
(and typed) languages, most of the use cases don't apply to dynamic
Javascript
The only legit use case I can think of is helping refactor tools to
rename properties (but even mismatch errors between strings and
properties names can be caught in compile time using modern
Typescript)

Em sex, 14 de jun de 2019 às 10:05, Stas Berkov
 escreveu:
>
> Can we revisit this issue?
>
>
> In C# there is `nameof`, in Swift you can do the same by calling
>
> ```
>
> let keyPath = \Person.mother.firstName
>
> NSPredicate(format: "%K == %@", keyPath, "Andrew")
>
> ```
>
> Let's introduce `nameof` in ES, please.
>
>
> Devs from TypeScript don't want to introduce this feature in TypeScript 
> unless it is available in ES ( 
> https://github.com/microsoft/TypeScript/issues/1579 )
>
> This feature is eagarly being asked by TypeScript community.
>
>
> I understand there are couple issues related to `nameof` feature in ES. They 
> are: minification and what to do if user already has `nameof` function.
>
>
> Minification.
>
> 1. If your code to be minimized be prepared that variable names will also 
> change.
>
> 2. (just a possibility) Minimizer can have option to replace 
> `nameof(someVar)` with result of `nameof` function.
>
>
>
> What if user already has `nameof` function.
>
> 1. To maintain status quo we can user `nameof` function having priority over 
> newly introduced language feature.
>
> 2. OR we can use `typeof` syntax, e.g. `nameof msg.userName` (// returns 
> "userName" string)
>
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



-- 
Atenciosamente,

Augusto Borges de Moura
___
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-30 Thread Augusto Moura
Just bringing to the table the other side of the discussion (not
agreeing with all of them)...
IIRC the biggest problem with a pick syntax is the syntactic noise
encouraging convoluted code. Even now just with destructuring and
arrow functions code can get messy really quickly. Another argument is
that a `pick` helper function is really easy to be implemented and the
problem that the syntax resolves is mostly aesthetic (even that is
questionable given the first argument, terseness != legibility).

IMHO just a `pick` function in the standard library would suffice most
of the problems that the syntax is trying to solve. Maybe something
like `Object.pick` or `Object.pickKeys` or
`Object.smooshIntoObjectTheValuesOf`

Em qui, 30 de mai de 2019 às 15:43, Bob Myers  escreveu:
>
> It would be fabulous if we could get one or more of these proposals 
> implemented as a Babel feature, but I think this would require the Babel team 
> making the relevant changes to Babylon, and my understanding is that they do 
> this only for features that have at least already started down the committee 
> track--understandable, but a kind of catch-22.
>
> You are one of many people whoi have wondered about this kind of feature over 
> the years, including dozens of Stack Overflow members, calling it by 
> different names, including picking, extended destructuring, extended dot 
> notation, picked properties, etc. My own proposal at 
> https://github.com/rtm/js-pick-notation is just one of several, although I 
> should mention that it represents the outcome of multiple iterations of 
> research and thinking, and its documentation is IMHO relatively clean and 
> complete, although it does not include the actual proposed changes to the 
> ECMAScript spec which need to be created at some point.
>
> Bob
>
> On Thu, May 30, 2019 at 11:29 AM Jacob Pratt  wrote:
>>
>> My understanding is that Babel does support proposals, even if they require 
>> new syntax. Of course, it would require changes to the parser that's beyond 
>> my understanding of the codebase. I'd certainly help out in whatever ways 
>> I'm able to.
>>
>> For the record, though, I actually had this idea completely separate from 
>> the proposal — I ran across it when searching to see if anyone else had 
>> proposed such a syntax/language feature.
>>
>> On Thu, May 30, 2019, 14:24 Bob Myers  wrote:
>>>
>>> I don't know what "community" means, other than a bunch of people 
>>> subscribing to this ML, and I can't imagine how one would define, or 
>>> achieve, or identify, a "consensus" of that community, or why or how the 
>>> community would vote on anything, or what such the results of such a vote 
>>> would mean.
>>>
>>> The very next step is to identify a champion. Such a champion would 
>>> presumably help to shape, review, and choose between alternatives for the 
>>> proposals. However, given the failure of my half-hearted efforts to find a 
>>> champion, and the fact that no one has emerged as champion over the several 
>>> years since these discussions started, allow me to be pessimistic.
>>>
>>> It's odd to me because features such as property spread/rest notation, and 
>>> before that destructuring, have clearly demonstrated the appetite of the 
>>> "community" for language changes to better support manipulation of 
>>> properties--not surprising, since objects and their properties can be 
>>> considered the fundamental data structures of the language. This specific 
>>> proposal has a relatively small syntactic footprint in my opinion, and 
>>> measures up well against the majority of criteria that people commonly 
>>> apply to language design decisions and have been documented on this list. I 
>>> can only conclude that wiser minds than my own have concluded that this 
>>> particular feature simply does not rise to the level of priority of other 
>>> features that are progressing down the pipeline.
>>>
>>> WIth regard to the notion of implementing this feature on a test basis, the 
>>> most obvious approach to doing that is as a Babel plug-in, but based on my 
>>> research--please-correct me if I'm wrong--Babel supports many kind of 
>>> transformations but not entirely new syntax as is the case here; that 
>>> requires essentialy rewriting internal parts of its parser. I have 
>>> experimented with a Sweet implementation with some success, but actually 
>>> I'm not really sure what that is supposed to demonstrate or if anyone would 
>>> care.
>>>
>>> Bob
>>>
>>> On Thu, May 30, 2019 at 12:29 AM guest271314  wrote:

 Not a rule. Just an email to this board.

 On Thu, May 30, 2019 at 7:26 AM Григорий Карелин  
 wrote:
>
> I'm new to this community, so I'd appreciate if you clarify: is that your 
> opinion or is it kind of rule written somewhere?
>
> чт, 30 мая 2019 г. в 09:59, guest271314 :
>>
>> > Wouldn't it be better to consolidate the decision? I mean as OP I vote 
>> > for `from`, but if majority will say they 

Re: Proposal: Lazy Error.message

2019-05-12 Thread Augusto Moura
Also, there's nothing preventing subclasses of Error to return a
function as message (or any other complex object). In chrome you can
also reassign a function to a existing error message, I didn't tested
others browsers. User interfaces/libraries can check if a message is a
function or not (giving your link to commonjs-assert I assume it was
your first idea)

Em sáb, 11 de mai de 2019 às 08:55, _ zaoqi  escreveu:
>
> Allow Error.prototype.message to be a Function
>
> It is useful in this case:
>
> https://github.com/browserify/commonjs-assert/pull/47
>
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: 1) Number (integer or decimal) to Array 2) Array to Number (integer or decimal)

2019-03-12 Thread Augusto Moura
> The proposal improves what is broken by not returning broken results relevant 
> to decimal numbers. The proposal allows users to get and set any portion of a 
> number using indexes of an array, which can then be converted back to a 
> number.

This is not a problem at all, that's not a single time I needed to do
anything like that in any code I worked with, neither most of the
developers here, and I dare to assume that even you used such
algorithm only a few times in your career. That a lot more complex
problems that need our attention, don't providing any real world
examples (aside from "solving this simple algorithm problem") will get
you anywhere

> If you are failing to interpret that as useful, that is your own issue. You 
> might as well state that Intl.NumberFormat.prototype.formatToParts does not 
> have any use. And further, JavaScript number implementation is fine just the 
> way that it is currently implemented, unless you decide that any proposal is 
> useful.

> The proposal is asking you people who claim to be specification authors to 
> _name_ each element of the resulting array, for consistency, again, the 
> example

> Number to array, array to number is just the first part of the procedure. The 
> part relevant to actually _naming_ the parts, for disambiguation, is what 
> propose here. If you are not interested, that is fine. Do not necessarily 
> need you to do anything. Will do for self as have and continue to do 
> independently, and name the discrete portions of the number arbitrarily, 
> without your input.

I don't think you understood the motivation of this mailing list and
the TC39 committee, the discussions usually are for additions for the
ECMAScript language (usually native APIs, syntax and implementation
details), concept naming and conventions are NOT responsibility of
this community. I suggest the reading of the TC39 proposal document
[1] and some proposals as examples [2]

At this point I'm just arguing with you for the sake of clarity to new
members that reach this thread

[1]: https://tc39.github.io/process-document/
[2]: https://github.com/tc39/proposals

Em ter, 12 de mar de 2019 às 13:54, guest271314
 escreveu:
>>
>> That's the premise that I'm challenging. Why is it simpler, and how does it, 
>> in any appreciable way, improve upon whatever you're asserting is "broken"?
>
>
> The same way that Intl.NumberFormat.prototype.formatToParts does. Though 
> takes the concept one step further by spreading each digit to an array. If 
> the number has a decimal, the decimal portion is set at a single element of 
> an array. If the decimal begins with a 0, continue until the first non-zero 
> number is reached, include that number in the decimal portion within the 
> array, and the remainder of the decimal portion is spread to remainder of 
> array elements
>
> Example:
>
> var n = numberToArray(100.00015); // [1, 0, 0, 0.0001, 5]
> arrayToNumber(n); // 100.00015
>
> The proposal improves what is broken by not returning broken results relevant 
> to decimal numbers. The proposal allows users to get and set any portion of a 
> number using indexes of an array, which can then be converted back to a 
> number.
>
> If you are failing to interpret that as useful, that is your own issue. You 
> might as well state that Intl.NumberFormat.prototype.formatToParts does not 
> have any use. And further, JavaScript number implementation is fine just the 
> way that it is currently implemented, unless you decide that any proposal is 
> useful.
>
> The array format is a simple data structure. Can be converted to JSON; can be 
> extended to include a description of each digit that is a user gets or sets; 
> e.g.,
>
> n[0].description // {digit: 1, place: 'hundreds', decimalSibling: true, 
> ...etc.}
>
>> With respect, your test cases confuse the issue more than they clarify. 
>> Questions on how you'd use this structure aside (which are still important), 
>> your test cases don't actually produce a structure in which digits are 
>> accessible by nth index (e.g., the 0-grouping behavior).
>
>
> Not sure what you mean? What are you confused about relevant to the test 
> cases? The code at the OP includes 1) the original proof of concept; 2) code 
> by  Stack Overflow user Shidersz which fixed two bugs in the original code. 
> Yes, the code at the OP does produce the expected result.
>
> You are misconstruing the proposal. The code already returns the expected 
> result. Do not ask for approval for anything. Just do and let the aftermath 
> settle to its own level.
>
> The proposal is asking you people who claim to be specification authors to 
> _name_ each element of the resulting array, for consistency, again, the 
> example
>
> var n = numberToArray(100.00015); // [1, 0, 0, 0.0001, 5]
>
> as an array users obviously do not have additional data about the values in 
> the array. What do you call the 0 at index 1? What do you call the 5 at index 
> 4?
>
> Before 

Re: Proposal: 1) Number (integer or decimal) to Array 2) Array to Number (integer or decimal)

2019-03-07 Thread Augusto Moura
There is space for improvement in low level programming in Javascript,
sure isn't the main focus of the language, but I don't think
unobtrusive proposals should be a problem. There's a lot of C/C++
number apis that would be really useful in some use cases (I'm
thinking now in matrix operations, graphics and games).

There's any prior art/work in your idea? Any C or other languages
functions, any spec'd norm (IEEE, ISO)? Or any library implementing it
that got popular in a niche? Having any examples of implementations
(aside for your own of course) would help your proposal immensely. I'm
not being toxic here this is a really specific use-case that I know
almost nothing.

About users not being concerned with your problem, we have to be
really cautious when supporting proposals, we can't just add every
function and syntax that solves someone problems, the language would
became bloated and complex rapidly. There's a fantastic thread [1]
that explains the point a lot better than me and you should definitely
read it.

Don't be angered if we don't give a lot of reception for your first
proposal, you can always improve your idea or get a new one.

Em qui, 7 de mar de 2019 às 21:56, guest271314  escreveu:
>
> Not sure if your failure thus far to gather what the proposal is actually 
> suggesting is based on your limited experimentation in using numbers in 
> JavaScript, or some other reason. That is ok. Your second point illustrates 
> the problem faced. Where your pseudo code uses String methods. That should 
> not be necessary. Further, where in the resulting array are you separating 
> the decimal portion of the number? How do you convert a decimal or irrational 
> number to JavaScript numbers in an array, accounting for the decimal? None of 
> those inquiries have standardized answers. You folks write standards. Only 
> asked the question on coding sites to not solely rely on own approach to 
> solving the inquiry, which ordinarily achieve before asking the question.
>
> It is not a "homework" project. Again, have no issues solving own coding 
> problems. It is not a coding challenge. It is a proposal to standardize 
> conversion of number to array <--> array to number. If you want to include 
> "ranges" in the proposal, have composed code for that output as well. The 
> issue is consistency (is an individual were to have such expectations) of 
> output in conversion in each of array to number and number to array. Am not 
> concerned with what you refer to as "apps", that is your *business*. The 
> proposal is for standardization of handling decimals to and from an array.
>
> That is obviously not a concern for you, or users here.
>
>
>
> On Fri, Mar 8, 2019 at 12:40 AM Isiah Meadows  wrote:
>>
>> > What part of the proposal, in your view, did not read "it'd be nice if 
>> > ..." number to array <--> array to number specification and 
>> > standardization?
>>
>> I think you missed my point in the first sentence. I'm saying the
>> first thing on your mind when creating proposals *shouldn't* be "it'd
>> be nice if ...". Please re-read that first sentence and you'll get
>> what I'm saying.
>>
>> > Not sure what you mean by "toy problems"? Do you mean only concepts that 
>> > meet *your* "toy" interests? Scale is irrelevant. The real world problem 
>> > is standardization of number to array, array to number conversion in 
>> > JavaScript.
>>
>> 1. Scale *is* mostly irrelevant here, even in my criticism. The only
>> requirement here is that it's in code you'd actually write when
>> building something. Code golf challenges aren't sufficient, since JS
>> doesn't optimize for that. It needs to be something genuinely useful,
>> useful enough to merit the added engine complexity as a result.
>> 2. Not everyone agrees the problem even exists - in fact, most of us
>> don't. "Number to array" is as simple as defining a `Symbol.iterator`
>> method on `Number.prototype` and using `[...num]`. "Array to number"
>> is just `+[...values]`, which evaluates to
>> `Number(String([...values]))`.
>>
>> -
>>
>> Isiah Meadows
>> cont...@isiahmeadows.com
>> www.isiahmeadows.com
>>
>> On Thu, Mar 7, 2019 at 7:29 PM guest271314  wrote:
>> >>
>> >> @guest When making a language proposal, the first thing that should be on 
>> >> your mind isn't , but the problems you're trying to solve. And these 
>> >> problems can't just be simple toy problems like a code golf challenge - 
>> >> they have to be real-world problems in code you write for sites, apps, 
>> >> libraries, and so on. If it's so niche as to be useless outside a simple 
>> >> challenge, you're unlikely to get any sort of support for adding it.
>> >> Also, when making a language proposal, it's your responsibility to 
>> >> persuade others of its usefulness. It's not others' responsibility to 
>> >> dispute it - they could just as easily ignore it and your proposal won't 
>> >> have a chance to be merged into the spec. You have to be the one to 
>> >> explain why it should be 

Re: Promise.resolve

2019-02-03 Thread Augusto Moura
It is the valid answer, subclassing is the reason behind the design choice
of Promise static members depending on `this`. If it was a good decision or
not is another topic. `Array.of` was designed in a different occasion and
static methods inheritance was not a subject at the time

Em dom, 3 de fev de 2019 22:04, Michał Wadas  This is not valid answer. Arrays can be subclassed too, but (1,Array.of)(2
> ,3) returns instance of Array.
>
> On Sat, Feb 2, 2019 at 10:20 PM Logan Smyth  wrote:
>
>> `Promise` can be subclassed, so the `this` context for `resolve` affects
>> what class is instantiated.
>>
>> On Sat, Feb 2, 2019 at 12:25 PM Sultan  wrote:
>>
>>> Was there any reason Promise.resolve was not afforded the ability to
>>> dispatch outside of `this` pointing to the `Promise` constructor?
>>>
>>> For example:
>>>
>>> const {resolve} = Promise
>>> resolve(1234)
>>>
>>> This currently throws.
>>> ___
>>> 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: Re: Proposal: Symbol Linked to `typeof`

2019-01-16 Thread Augusto Moura
The module system is not filesystem based, but URL based, that's a lot
of differences between the two, URLs are designed to be unique and be
storage/protocol agnostic in most networks. Others languages are
following similar paths, Go for example even allows you to import
entire github projects directly in source code, Deno (a experimental
Node-like platform, made by the Node former creator) follows the same
direction. In a distributed world, URLs work really good as truly
Global Unique Identifiers

In my opinion there's no better way to uniquely identifying than
comparing it with the actual reference. But if you want a qualified
name so badly, the only way I know is writing them manually, maybe you
could use some external tool to automate this step, something like
jscodeshift or a babel plugin. You could use decorators for runtime
injection metadata (probably a parameterized namespace name)

``` js

const rootNamespace = 'com.foo'

const qualifiedName = (...namespaces) => (clazz) => {
  const namespacesJoined = namespaces.join('.');
  clazz.qualifiedName = rootNamespace + (namespacesJoined ? '.' +
namespacesJoined : '') + '.' + clazz.name;
};

@qualifiedName('domain', 'package')
class Foo {
}

console.assert(Foo.qualifiedName === 'com.foo.domain.package.Foo')
```
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Re: Proposal: Symbol Linked to `typeof`

2019-01-16 Thread Augusto Moura
I don't think string namespaced names are the right feature here

Namespaces are intended mainly to avoid conflicts with names when
sharing a global scope (like when using classpath in Java, or libs in
C++)
Javascript already solves this problems with modules, you can always
guard your code with instanceof and the right instance of your class,
you don't need "qualified names"
``` js
// flow.js
export class Flow {
}
```
``` js
// main.js
import { Flow } from './flow.js'; // we don't need namespaces, a "file
path" already resolves conflicts for us

const doSomething = (obj)  => {
  if (obj instanceof Flow) {
// ...
  }
}
```

You can also customize the instanceof operation with `Symbol.hasInstance`
``` js
class Flow {
  // Normally you would check the minimum contract required to any guard work
  // Probably bad idea to override in most of the cases
  static [Symbol.hasInstance](obj) {
return '_flow' in obj;
  }
}

// Note that the control is inverse to your proposal the Class
determines if a value is instance (this why it's static)
// Without altering `Flow[Symbol.hasInstance]` just expected objects
will pass the check in `doSomething`
doSomething({}); // doesn't work
doSomething({ __proto__: Flow.prototype }); // doesn't work
doSomething({ _flow: undefined }); // actually works
```

~string qualified names are so 20th century~


Em qua, 16 de jan de 2019 às 01:48, Randy Buchholz
 escreveu:
>
> Right. Misappropriating a symbol corrupts its intent. As ES moves in a more 
> towards a more “class-ish” feel, and people start writing more classes, a 
> type/namespace system isn’t far behind. Implementing some symbols to support 
> this helps drive some standard approaches and discourages symbol 
> misappropriation.
>
>
>
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



--
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Class Templates

2019-01-16 Thread Augusto Moura
In the proposal:
> ``` js
> class SizedArray extends Array {
>
>   constructor(...args) {
> if(args.length > size) throw new SyntaxError('Argument size is too big.')
> super(...args)
>   }
>   push(i) {
> if(this.length + 1 > size) throw new SyntaxError('Cannot push items 
> anymore, array too big.')
> super.push(i)
>   }
> }
> ```
> Usage:
> Usage is simple, and obvious.
> ``` js
> // ...
> let somethingElse: A = new A;
> ```

I don't think the syntax is obvious. What will happen in the if inside
the constructor? What value `size` would receive? Infinity? undefined?
The `Number` function?
That's no way templates will ever work like that in Javascript, it
doesn't makes any sense, C++ templates were implemented to support
generic static allocation and safe typings, neither of this features
applies to Javascript (and probably never will). Your example could
easily be written with constructor arguments (like any sane OOP
language), that's not a problem to be solved here

``` js
class SizedArray extends Array {
  constructor(size, ...args) {
if (args.length > size) throw Error();
super(args);
  }
}
```

Em ter, 15 de jan de 2019 às 17:01, IdkGoodName Vilius
 escreveu:
>
> See: 
> https://github.com/CreatorVilius/ecmascript-proposals/blob/master/proposal-class-templates.md
>
>
>
> I think having Class Templates in JavaScript would be awesome thing and 
> should be implemented. But that’s just my opinion.
>
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Array.create and Function.create

2019-01-10 Thread Augusto Moura
If you don't want the iterable features neither the own properties,
what're the benefits over a object indexed by numbers `const o =
Object.create(null); o[0] = 12; ...`?
About the other function proprosal (`Function.create`) I don't see any
benefits in day to day use having a function without prototype

If you are interested in a performatic barebones fixed-sized arrays
(like your C example) you should read about ArrayBuffers and Typed
Array views[1]. Actually it is the closest to your example as
Javascript could potentially get.

[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays

Em qui, 10 de jan de 2019 às 07:35, Sultan  escreveu:
>
> >Why would this be better than `const a = []; Object.setPrototypeOf(a, null)`?
>
> In that example "a" value would still have "own" properties like length.
>
> a = Array.create(null, 10)
>
> Wouldn't have any own or prototype properties by design; It is mean to be 
> "bare-bones" or as close to a C-like:
>
> a = malloc(sizeof(void*)*10)
>
> as JavaScript could potentially get.
>
> On Thu, Jan 10, 2019 at 11:54 AM Jordan Harband  wrote:
>>
>> Why would this be better than `const a = []; Object.setPrototypeOf(a, null)`?
>>
>> On Thu, Jan 10, 2019 at 12:09 AM Sultan  wrote:
>>>
>>> >An array with no prototype wouldn't have any of the iteration methods on 
>>> >it...
>>>
>>> Yes, that is what is intended with this, similar to an Object.create(null) 
>>> object with number-ed keys.
>>>
>>> Alternatively one could look at the objects created from this to be the 
>>> "bare-bones" structure around these data-structures.
>>>
>>> That is the in-existence of prototypes and own properties like "length" 
>>> makes it clear that these "flat" objects are intended as author managed 
>>> objects.
>>>
>>> There are is no visible default prototype or own properties because the 
>>> author will create, expose and managed these for the data-structure 
>>> explicitly if need be or more commonly choose to not expose the 
>>> data-structure at all and use these for low-level internal book keeping for 
>>> other abstractions.
>>>
>>> This would create a new ceiling(or ground-level) for how "low-level" one 
>>> could go with JavaScript if these where part for the language and as a 
>>> secondary consequence allow engines to make stronger assumptions with 
>>> regards to operations on these structs.
>>>
>>> On Thu, Jan 10, 2019 at 9:48 AM Jordan Harband  wrote:

 An array with no prototype wouldn't have any of the iteration methods on 
 it; a function with no prototype wouldn't have .call/.bind/.apply - length 
 and name are own properties of functions, and length is an own property of 
 an array, so you'd get those regardless.

 (`Array.from({ length: 1000 })` already creates an array of length 1000 
 without holes, fwiw)

 On Wed, Jan 9, 2019 at 10:43 PM Sultan  wrote:
>
> Identical to Object.create but for Arrays and Functions.
>
> This method will allow you to create arrays with no prototype.
>
> This would allow authors the ability to use array objects as state 
> containers without the need to resort to index-based objects with
>
> Object.create(null, length)
>
> When you want to both use an array-like struct as both a property and 
> index-able map.
>
> A side-effect of this would afford engines a strong heuristic for 
> avoiding holey-array look-ups operations when there's no prototype to 
> walk.
>
> For example the following would create an array with a length of 1000 
> without "holes".
>
> const arr = Array.create(null, 1000)
>
> In addition this could also apply to functions with
>
> Function.create(null, () => {})
>
> When you want to use functions as state-containers but don't want any of 
> the implicit properties(length, name) etc.
> ___
> 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



-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: New: proposal-common-member-modifiers

2018-12-02 Thread Augusto Moura
Extracted from the proposal [1]:
> Instead of waiting for the community to define and agree upon decorators for 
> these purposes, why not define them now?

In my opinion this is not how things should be done, in my opinion we
actually should follow user-land patterns and help modifying/extending
the language in this patterns pain points. We saw that in almost every
new feature in the language since Harmony (not a coincidence, it's was
actually decided to be this way), community agreement is a important
factor in the process (I really don't know why it's not in the TC39
process document [2], maybe is implied?). A lot of problems in
Javascript ~and probably all other languages in existence~ arose from
expected usefulness, just to be tagged as a foot gun or bad design by
the community, and not used at all.

That being said, I think decorators already provide all the need for
this "runtime-modifiers" keywords, and new keyword-like modifiers will
only add complexity to the language, as we would have 2 declarative
ways of doing the same thing (or worse, the community decide in a
different behavior for the analogue decorators, and probably one of
the ways would be discouraged and become spec garbage).

PS.: Sure there are cases were the community is really divided and
things don't move because of that, and some of this cases are merged
in the spec without total agreement at the end. But in my opinion this
slow process and discussion is a good thing, we cannot merge something
just to because it seems like a good feature. Also I'm not a TC39
member, it's my opinion based in similar discussions in the past,
maybe some real member can clarify it better or correct me if I'm
wrong.

[1] https://github.com/rdking/proposal-common-member-modifiers#motivation
[2] https://tc39.github.io/process-document/
Em dom, 2 de dez de 2018 às 04:49, Ranando King  escreveu:
>
> Since some form of data is going to land in ES class syntax, it would be a 
> good idea if the capabilities of a property descriptor were also exposed for 
> all public properties.
>
> https://github.com/rdking/proposal-common-member-modifiers
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal for faster this assignments in constructor functions

2018-11-28 Thread Augusto Moura
I forgot the links in my last email, here they are:
[1] https://github.com/tc39/proposal-decorators
[2] 
https://docs.google.com/document/d/1Qpkqf_8NzAwfD8LdnqPjXAQ2wwh8BBUGynhn-ZlCWT0
Em qua, 28 de nov de 2018 às 20:48, Augusto Moura
 escreveu:
>
> In the ~maybe long~ future , after the current decorators proposal [1], we 
> can start thinking about a Method Parameter Decorator (already proposed [2]), 
> we could do something like:
>
> ``` js
> class Foo {
>   constructor(@field foo) {
>   }
> }
> ```
>
> In my opinion, it would be a much more powerful approach
> Em qua, 28 de nov de 2018 às 16:33, Simo Costa  
> escreveu:
> >
> > In costructor functions and in the constructor() method in ES6 classes is 
> > easily to fall in the following pattern:
> >
> > F(par1, par2, ..., parN) {
> >   this.par1 = par1;
> >   this.par2 = par2;
> >   ...
> >   this.parN = parN;
> > }
> >
> >
> > So my proposal is to avoid those repetitions  by prefixing a dot . to each 
> > parameter:
> >
> > F(.par1, .par2, ..., .parN) {}
> >
> > Simple but quite useful. More info here: 
> > https://github.com/jfet97/proposal-fast-this-assignments
> >
> >
> >
> > ___
> > es-discuss mailing list
> > es-discuss@mozilla.org
> > https://mail.mozilla.org/listinfo/es-discuss
>
>
>
> --
> Atenciosamente,
>
> Augusto Borges de Moura



-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal for faster this assignments in constructor functions

2018-11-28 Thread Augusto Moura
In the ~maybe long~ future , after the current decorators proposal
[1], we can start thinking about a Method Parameter Decorator (already
proposed [2]), we could do something like:

``` js
class Foo {
  constructor(@field foo) {
  }
}
```

In my opinion, it would be a much more powerful approach
Em qua, 28 de nov de 2018 às 16:33, Simo Costa
 escreveu:
>
> In costructor functions and in the constructor() method in ES6 classes is 
> easily to fall in the following pattern:
>
> F(par1, par2, ..., parN) {
>   this.par1 = par1;
>   this.par2 = par2;
>   ...
>   this.parN = parN;
> }
>
>
> So my proposal is to avoid those repetitions  by prefixing a dot . to each 
> parameter:
>
> F(.par1, .par2, ..., .parN) {}
>
> Simple but quite useful. More info here: 
> https://github.com/jfet97/proposal-fast-this-assignments
>
>
>
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



-- 
Atenciosamente,

Augusto Borges de Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Promise.finally not really final

2018-09-07 Thread Augusto Moura
Why would you destroy a node and `.then()` pause it? It doesn't make
sense even in plain English. If the contract of the method (expected
behavior) is to destroy the internal node, using it after is a error.
You can easily reimplement your use case reversing the logic:

 js
setTimeout(() => {
  demo.node.pause();
  demo.destroy();
}, 3000);


Another solution is to implement a `beforeDestroy` event emitter and
listen to it, this way is certain that the code will be executed
always before the node is gone and after any async destroy logic:

 js
class Demo {
  constructor(el) {
this.beforeDestroy = new EventEmitter();
// Using the @angular/core EventEmitter because is more "close to English"
this.node = el;
  }
  destroy() {
return new Promise(resolve => resolve())
  .then(() => this.beforeDestroy.emit())
  .finally(() => {
this.node = null;
  });
  }
}

const demo = new Demo(document.querySelector('video'));

demo.beforeDestroy.subscribe(() => {
  demo.node.pause();
});

setTimeout(() => {
  demo.destroy();
}, 3000);


Anyway, the `then`, `catch` and `finally` methods mimic the serial
try/catch/finally, simply doesn't make sense finally statements
protecting code beyond it's try block definition, and chaining new
`.then`s _are_ beyond the promise definition. Also, async functions
already has finally blocks implementations in the same way as the
current `.finally` method spec, implementing a different behaviour
would be unnecessarily confusing.
Em sex, 7 de set de 2018 às 16:16, Jon Ronnenberg
 escreveu:
>
> I know I am late to the game and that Promise.prototype.finally is already in 
> stage 4 but(!).
>
> It's just not very useful to have a final function when it's not the final 
> function to run. If it's suppose to be for cleanup, then the current 
> implementation is seriously lacking usefulness.
>
> Consider the following example:
>
>class="i-am-the-element"
>   autoplay="autoplay"
>   controls="controls">
>  src="http:\/\/play.dogmazic.net\/play\/index.php?type=song=22951=-1=Black%20poetry%20-%20Aime-.mp3">
> 
> 
>   class Demo {
> constructor (element) {
>   this.node = element
> }
> destroy () {
>   return new Promise(resolve => {
> // do something or nothing
> resolve()
>   }).finally(() => {
> // schedule for DOM removal
> this.node = null
>   })
> }
>   }
>
>   const demo = new Demo(document.querySelector('.i-am-the-element'))
>
>   setTimeout(() => {
> demo.destroy().then(() => {
>// will throw an error because finally was run before
>   demo.node.pause()
> }).catch(console.error)
>   }, 3000)
> 
>
> One grand idea about promises is to delegate and compose asynchronous 
> functions, but the current implementation can not be used to for code 
> delegation.
>
> From the top of my head the only way to have consumer code,  tap into an 
> execution process is to use callbacks which is what Promises were suppose to 
> help alleviate.
>
>class="i-am-the-element"
>   autoplay="autoplay"
>   controls="controls">
>  src="http:\/\/play.dogmazic.net\/play\/index.php?type=song=22951=-1=Black%20poetry%20-%20Aime-.mp3">
> 
> 
>   class Demo {
> constructor (element) {
>   this.node = element
> }
> destroy (callback) {
>   // do something or nothing
>   try {
> callback()
>   } finally {
> // schedule for DOM removal
> this.node = null
>   }
> }
>   }
>
>   const demo = new Demo(document.querySelector('.i-am-the-element'))
>
>   setTimeout(() => {
> demo.destroy(() => {
>   demo.node.pause()
> })
>   }, 3000)
> 
>
> If at all possible, please amend to the spec before it's too late! ... or 
> just drop it.
>
> My current use-case is that I work with PSPDFKit and can not get DOM access 
> but rather schedule removal of DOM nodes via their API, but I can pause 
> audio/video - just not using Promise.prototype.finally as it is currently 
> envisioned.
>
> Regards, Jon
>
> PS. Tested in Firefox 63.0b3 and Safari 11.1.2
> Here is a polyfill if you need: 
> https://cdn.polyfill.io/v2/polyfill.minify.js?features=Promise.prototype.finallyflags=gated
>
> ___
> 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: constructor, super, and data members issue

2018-08-25 Thread Augusto Moura
24-08-2018 19:29, Aaron Gray :

>
> Yeah it does look like its badly "broken by design".
>

Why this behaviour is broken? Every OOP language that I worked with
behaves de same way, and there's not many developers complaining about
it. If you want to use a property that might be overrided in a
subclasss you need to use a method and make the source of the data
more versatile (in Java and others similiar languages we have to
implement it using getter methods). Luckily Javascript doesn't need
getter and setters methods to make a property overridable because of
getter and setters descriptors, so we can workaround the first example
easily:

``` js
class Bar {
  bar = 'in bar';

  constructor() {
console.log(this.bar)
  }
}

class Foo extends Bar {
  _initiedSuper = false;
  _bar = 'in foo';

  constructor() {
super();
this._initiedSuper = true;
  }

  get bar() {
return this._bar;
  }

  set bar(val) {
if (this._initiedSuper) {
  this._bar = val;
}
  }
}

new Foo(); // will log 'in foo'
```

*I have to say the relaying that the super constructor will use the
bar property and workarounding it **is a bad practice** and should be
avoided at any costs. The contract with the super class constructor
should rely only on the super call, these situations just reveal bad
design choices in the super class. Logan Smyth example is the correct
answer to this problem*


25-08-2018 01:28, Jordan Harband :

>
> Personally I think a design where the superclass relies on any part of the
> subclass is "broken by design"; but certainly there's ways you can achieve
> that.
>

Of course is not broken. The super class has a contract with a
parametrized option, it can be used in subclasses or just in a
constructor call `new Base({ idAttribute: 'foo' })`, if it has a
default value for that is not a sub class concern. When refactoring
code adding defaults and "lifting" parameters are very common ~not
only on OOP~ and relying that the super class is using some property
in the constructor is the real "broken by design".
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Promise capability support

2018-07-21 Thread Augusto Moura
Reject and resolve static methods are not introducing a new ~maybe
dangerous~ pattern into the language, they are just isolating a factory for
a common use case (creating a promise wrapping a well know value at the
time of execution), deferreds add a whole lot of indirection in the table,
that might lay some traps for non-experienced developers and promote some
bad designs or confusing code.

Em sáb, 21 de jul de 2018 às 15:20, Isiah Meadows 
escreveu:

> > I think what Jordan means, it's that the deferred has it use case, but
> > probably we don't want it in Javascript native library. There's a lot of
> > mature libraries implementing deferred wrappers and most of them are
> Promise
> > like compatible, and even if you cannot use libraries or don't want to,
> you
> > can easily implement a Promise extension and use it yourself.
>
> Jordan, is this accurate? It wasn't what I read of it, unless you sent
> something that mistakenly missed the list.
>
> If that *is* the case, I don't see much precedent:
> `Promise.resolve`/`Promise.reject` also hit that bar just as quickly,
> if not *quicker*:
>
> ```js
> // Exact polyfills, assuming `IsPromise` as per 25.6.1.6 is exposed
> globally.
> // https://tc39.github.io/ecma262/#sec-ispromise
> Promise.resolve = Promise.resolve || function (value) {
> if (IsPromise(value) && value.constructor === Promise) return value
> let resolve
> let promise = new this((r, _) => { resolve = r })
> resolve(value)
> return promise
> }
>
> Promise.reject = Promise.reject || function (value) {
> let reject
> let promise = new this((_, r) => { reject = r })
> reject(value)
> return promise
> }
> ```
>
> -
>
> Isiah Meadows
> m...@isiahmeadows.com
> www.isiahmeadows.com
>
>
> On Fri, Jul 20, 2018 at 12:15 PM, Augusto Moura
>  wrote:
> > I think what Jordan means, it's that the deferred has it use case, but
> > probably we don't want it in Javascript native library. There's a lot of
> > mature libraries implementing deferred wrappers and most of them are
> Promise
> > like compatible, and even if you cannot use libraries or don't want to,
> you
> > can easily implement a Promise extension and use it yourself.
> >
> > Interesting enough, I got a really weird case (reads contraintuitive, I'm
> > pretty sure the semantics of the error are right) extending the Promise
> > class to exemplify a simple Deferred implementation, the code:
> >
> > ``` js
> > class Deferred extends Promise {
> >   constructor(factory) {
> > super((resolve, reject) => {
> >   Object.assign(this, { reject, resolve });
> >   factory(resolve, reject);
> > });
> >   }
> > }
> >
> > const d = new Deferred(() => {});
> > ```
> > The problem is the usage of `this` before calling the super constructor
> > (even when the using in the super call itself). I wonder with it there
> are
> > any ways of capturing the super constructor arguments in a Base class
> using
> > class syntax. You probably can get the arguments in a old "function
> class"
> > syntax (can be done weakmaps too). We can probably start ~yet~ another
> > thread on Promises, about this problem (supposing there's no way of
> passing
> > `this` to the promise factory).
> >
> > Em sex, 20 de jul de 2018 às 03:03, Isiah Meadows <
> isiahmead...@gmail.com>
> > escreveu:
> >>
> >> First, I do get that not all uses of deferred-like objects really
> >> merit the need for a deferred. For example, [here][1], I saved the
> >> resolver and pulled the state out from the main closure to make the
> >> state easier to follow. You could argue a deferred isn't really
> >> necessary since I only care about the `resolve` function, and nothing
> >> else. It's also pretty trivial to factor it back into a closure where
> >> it was originally.
> >>
> >> [1]:
> >>
> https://github.com/isiahmeadows/thallium/blob/master/lib/core/tests.js#L337-L428
> >>
> >> But it's when external forces control them indirectly through a state
> >> machine or similar, that's when it becomes necessary. I have some
> >> closed-source uses, but here's a couple concrete examples I have in
> >> OSS code:
> >>
> >> 1. Here, I have to treat it like a continuation because I have to wait
> >> for an IPC protocol sequence to complete before it resolves/rejects:
> >>
> >>
> https://github.com/isiahmeadows/invoke-parallel/blob/master/lib/api.js#L144-L147
> >> 2. Her

Re: Promise capability support

2018-07-20 Thread Augusto Moura
You are right, I didn't know you can use variables before calling the super
constructor (a Java thing).
So yeah, it's pretty easy to extend a Promise to externalize resolve and
reject

---
PS: Sorry about my last email last paragraph grammar, I'm yet getting used
to write long texts in English

Em sex, 20 de jul de 2018 às 15:57, Richard Gibson 
escreveu:

> On Fri, Jul 20, 2018 at 12:15 PM Augusto Moura 
> wrote:
>
>> Interesting enough, I got a really weird case (reads contraintuitive, I'm
>> pretty sure the semantics of the error are right) extending the Promise
>> class to exemplify a simple Deferred implementation, the code:
>>
>> ``` js
>> class Deferred extends Promise {
>>   constructor(factory) {
>> super((resolve, reject) => {
>>   Object.assign(this, { reject, resolve });
>>   factory(resolve, reject);
>> });
>>   }
>> }
>>
>> const d = new Deferred(() => {});
>> ```
>> The problem is the usage of `this` before calling the super constructor
>> (even when the using in the super call itself).
>>
>
> Isn't the solution the pattern we've already seen?
> ```js
> class Deferred extends Promise {
>   constructor(factory) {
> const methods = {};
> super((resolve, reject) => Object.assign(methods, { resolve, reject })
> );
> Object.assign(this, methods);
> factory(this.resolve, this.reject);
>   }
> }
> ```
>
-- 
Augusto Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Small Proposal "!in"

2018-07-20 Thread Augusto Moura
The only use that came to mind was detecting a property descriptor in a
prototype chain. Sure is not a day to day use case, but it's useful when
writing libraries that involve descriptor modifications (decorators, for
example, will largely involve it). Recently I had to get the descriptor of
properties in a potencial deep inheritance (current Object helpers only
return own descriptors), and used the `in` operator to guard the prototype
recursive search.

``` js
const searchRecursivelyPropDescriptor = (obj, prop) =>
  !obj
? undefined
: Object.getOwnPropertyDescriptor(obj, prop) ||
searchRecursivelyPropDescriptor(Object.getPrototypeOf(obj), prop);

const getPropertyDescriptor = (obj, prop) =>
  prop in obj ? searchRecursivelyPropDescriptor(obj, prop) : undefined;
```

Anyways, we can't simply ignore the operator, if we are getting a
`!instance` and opening precedence to future operators (`!on` or `!hasOwn`)
I don't see any problems with a `!in`. Legacy bad design should not affect
language consistency of new features.

Em qui, 19 de jul de 2018 às 12:07, Mike Samuel 
escreveu:

> On Thu, Jul 19, 2018 at 10:40 AM Augusto Moura 
> wrote:
>
>> Of couse the usage of `in` is most of the time is not recommended, but it
>> has it place.
>>
>
> What places does it have?
> I remain unconvinced that `in` has significant enough use cases to warrant
> high-level ergonomics
> were it being proposed today.
>
> It exists, and it'll probably never be removed from the language, but I
> don't think it should be taught
> as a good part of the language, and linters should probably flag it.
>
> --
Augusto Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Promise capability support

2018-07-20 Thread Augusto Moura
problem.
> > The other I eventually replaced with the following kind of pattern:
> >
> > ```
> > function createPromise(resolver, rejector) {
> >   return new Promise((resolve, reject) {
> > resolver.then(resolve);
> > rejector.then(reject);
> > });
> > }
> > ```
> >
> > Obviously the way this works it that to create a promise "controllable"
> from
> > "the outside",
> > you create your own resolver and rejector promises to pass to
> > `createPromise`,
> > such that they trigger when you need them to.
> > To put it a different way, instead of getting back and passing around
> > deferred-like objects,
> > which seems to be a massive anti-pattern to me,
> > the client creates their own promise-controlling promises designed to
> > trigger at the right time.
> >
> > Bob
> >
> > On Fri, Jul 20, 2018 at 9:07 AM Jordan Harband  wrote:
> >>
> >> I don't think the Deferred pattern is a good primitive to have in the
> >> language, and it's a pretty trivial primitive to write yourself if you
> need
> >> it.
> >>
> >> On Thu, Jul 19, 2018 at 6:13 PM, Isiah Meadows 
> >> wrote:
> >>>
> >>> Sometimes, it's *very* convenient to have those `resolve`/`reject`
> >>> functions as separate functions. However, when logic gets complex
> >>> enough and you need to send them elsewhere, save a continuation, etc.,
> >>> it'd be much more convenient to just have a capability object exposed
> >>> more directly rather than go through the overhead and boilerplate of
> >>> going through the constructor with all its callback stuff and
> >>> everything.
> >>>
> >>> It's surprisingly not as uncommon as you'd expect for me to do this:
> >>>
> >>> ```js
> >>> let resolve, reject
> >>> let promise = new Promise((res, rej) => {
> >>> resolve = res
> >>> reject = rej
> >>> })
> >>> ```
> >>>
> >>> But doing this repeatedly gets *old*, especially when you've had to
> >>> write it several dozen times already. And it comes up frequently when
> >>> you're writing lower-level async utilities that require saving promise
> >>> state and resolving it in a way that's decoupled from the promise
> >>> itself.
> >>>
> >>> -
> >>>
> >>> So here's what I propose:
> >>>
> >>> - `Promise.newCapability()` - This basically returns the result of
> >>> [this][1], just wrapped in a suitable object whose prototype is
> >>> %PromiseCapabilityPrototype% (internal, no direct constructor). It's
> >>> subclass-safe, so you can do it with subclasses as appropriate, too.
> >>> - `capability.resolve(value)` - This invokes the implicit resolver
> >>> created for it, spec'd as [[Resolve]].
> >>> - `capability.reject(value)` - This invokes the implicit rejector
> >>> created for it, spec'd as [[Reject]].
> >>> - `capability.promise` - This returns the newly created promise.
> >>>
> >>> Yes, this is effectively a deferred API, but revealing constructors
> >>> are a bit too rigid and wasteful for some use cases.
> >>>
> >>> [1]: https://tc39.github.io/ecma262/#sec-newpromisecapability
> >>>
> >>> -
> >>>
> >>> Isiah Meadows
> >>> m...@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
>
-- 
Augusto Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Small Proposal "!in"

2018-07-19 Thread Augusto Moura
In most of the use cases of checking if a property is in the prototype
chain (checking a protocol for example) you *do* want to trigger getters
and Proxy traps. When interfacing with a object a developer doesn't need to
be concerned with the implementation behind, if a getter or proxy trap does
a intensive computation or has side effects, it's all bad class/object
design fault. A common example when you want to check a property "return"
rather than it's existence it's virtual properties or class refactoring:
``` js
// old implementation
class Foo {
  constructor() {
this.foo = 46;
  }
}

// post refactoring
class Foo {
  // implements something different

  // Product of refactoring, undefined it's a placeholder here
  //it can be any value that makes sense in the refactoring
  get foo() { return undefined; }
  set foo(_) {}
}
```
Of course there's some use cases to use property check without triggering
side effects (mostly when working with property descriptors), but the
majority of "property existence check" lays on interface assertion and a
typeof check it's ~generally~ the right choice.

About the `!in` operator, I don't see any problem in it. Of couse the usage
of `in` is most of the time is not recommended, but it has it place. Also
it puts precedence to future operators (like the `hasOwn` proposed here).

Em qui, 19 de jul de 2018 às 10:26, Michael Theriot <
michael.lee.ther...@gmail.com> escreveu:

> > '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.
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-- 
Augusto Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: [Proposal] New syntax for lazy getters

2018-06-28 Thread Augusto Moura
*An errata in my code*
The getter is mutating the object with a enumerable property, so
consecutives invocations of JSON.stringify will result different from
the first call (if the property is yet not initialized). The current
problem is:
```js
JSON.stringify(foo) // Returns "{"bar":3}"
// After the first bar "get" the object has now another property "_bar"
JSON.stringify(foo) // Returns "{"bar":3,"_bar":3}"
```
I did it as a quick loose scratch and didn't test it. A more robust
implementation (with a helper function) probably would use closures to
maintain the factory state. As exemplified:
```js
const defineLazyProp = (obj, propName, valueFactory) => {
  let selfDestroyingFactory = () => {
const value = valueFactory();
selfDestroyingFactory = () => value;
return value;
  };

  return Object.defineProperty(obj, propName, {
enumerable: true,
configurable: false, // It might be discussed if the lazy prop
should be configurable or not
get() {
  return selfDestroyingFactory();
},
  });
};

const foo = {};

defineLazyProp(foo, 'bar', () => 3);

// This should work correctly now
console.log(JSON.stringify(foo));
console.log(JSON.stringify(foo));
```
It's a bit more verbose, but it's the best way I can think of
"ponyfilling" it at the moment.

On June 28, 02:45, Isiah Meadows  wrote:
>
> I agree the main proposal is long and complex, but this kind of addition 
> could be designed with little effort to "fall out of the grid", since it has 
> so much in common with classes already (properties, getters/setters, 
> methods). The main question is with properties, but those are easy to just 
> leave out, since function calls do just as well.
>

You are right, but yet I prefer to get the classes decorators
advancing to a greater stage as soon as possible, a objet literal
decorator would be a easy extension to the current proposal. By the
way, I was comparing with the 2 others proposals by the fact that they
are more like "extensions" to the main proposal, not by the complexity
(as far as I know, mix the 3 decorators proposals in one would stall
most of the work), but yeah they really are different beasts.
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: [Proposal] New syntax for lazy getters

2018-06-27 Thread Augusto Moura
On June 27, 2018 09:23, kai zhu  wrote:
> what would happen if you tried to JSON.stringify foo? a core-value of
javascript to industry is as an idiot-proof/least-surprise language for
serializing json-data across browser <-> server.  junior-programmers who
naively employ hard-to-serialize things like custom-getters in their
low-level code, mostly end up annoying senior-programmers when they have to
debug high-level integration-code that have problems baton-passing those
states around.

Depends on the chosen implementation (which will be open for discussion for
sure). The Groovy AST transformation annotation `@Lazy` for example
translates the field into a getter (without a setter, making it virtually a
readonly field) which initializes the field once at the first invocation
(there is a example of the generated code at Groovy docs[1]). If we follow
this path we can easily implement it in Javascript as a enumerable get
property descriptor. About `JSON.stringify`, it renders all enumerable
properties of a object, including getters, so it will initialize the field
and represent it as any other property. My previous decorator example could
be loosely interpreted as:

```js
const foo = {
  get bar() {
if (!this.hasOwnProperty('_bar')) {
  this._bar = 3;
}
return this._bar;
  },
};

// JSON.stringify would write the correct bar value, initalizing it if
necessary
JSON.stringify(foo) // "{"bar":3}"
```

We could make a setter too, but the logic to implement it it's a lot more
complex and subject to confusion

On June 27, 2018 10:11, Isiah Meadows  wrote:
> If you're wanting to propose new places for decorators, you'd have much
better luck here: https://github.com/tc39/proposal-decorators

I think that the main proposal is already long and complex, maybe it's a
better idea to finalize it first and then start a new proposal about this
others decorators places (as with function expression decorators and
function parameters decoratos).

[1] http://groovy-lang.org/metaprogramming.html#xform-Lazy
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: [Proposal] New syntax for lazy getters

2018-06-12 Thread Augusto Moura
I don't think a new keyword is the right path here. For classes lazy fields
can easily be implemented via decorators in the last proposal[1] (also,
Groovy has previous work implementing a `@Lazy` annotation[2] with AST
transformations for the same use case). In code something like:
``` js
const lazy = (fieldMetadata) => {
  // change the field value in descriptor to a lazy factory
};

class Foo {

  @lazy bar = slowCalculation();

  @lazy statements = (() => {
 if (this.bar > 0) {
   return fooify();
 } else {
   return barify();
 }
  }());

}
```

What it's doesn't cover (and in my opinion should be the focus of a new
proposal) is Decorators for literal objects. Something like the code below
is yet not proposed:

``` js
const foo = {
  @lazy bar: 3,
};
```

I didn't made a deep search in ESDiscuss history but I remember this
feature being mentioned sometime ago.

[1]: https://github.com/tc39/proposal-decorators
[2]: http://groovy-lang.org/metaprogramming.html#xform-Lazy
-- 
Augusto Moura
___
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 Augusto Moura
Assuming `Object.keys` has the same order as a simple `for..in` (as stated
in mdn)[
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys],
we can already implement a function to build a iterator from object keys,
and then we can destruct or use others helpers to minimize the array
creation. Something like:

``` js
function* keysIterator(obj) {
  for (const key in obj) {
if (obj.hasOwnProperty(key)) {
  yield key;
}
  }
}
const obj = { foo: 12, bar: 89 };

// Using destructuring
const [firstProp, secondProp, ...othersKeys] = keysIterator(obj);

// Using some helper functions
const props = take(2, 10)(obj);
```

The discussion IMHO is if we need that as a built in helper (maybe
`Object.keysIterator()`), and if we need to extend it to `Object.values`
and `Object.entries`.

Em ter, 24 de abr de 2018 às 10:54, somonek <somo...@gmail.com> escreveu:

> Hi all,
>
> Assuming that
>
> const myObject = {
>   one: 123,
>   two: 456,
> };
>
> could
> myObject[in 0] === 'one' // true
>
> be a better alternative of
> Object.keys(myObject)[0]
>
> and
> myObject[in 3] === undefined
>
> without the need to convert all the object keys into an array, but
> directly accessing one.
>
> Best,
> Serghei
>
> ___
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-- 
Augusto Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: EcmaScript Proposal - Promised functions

2018-04-12 Thread Augusto Moura
Also it can be already be implemented in user land with high orders
functions:

``` js
const sleep = promised(function (time) {
  window.setTimeout(() => this.resolve(), time);
});
```

A simple implementation of a `promised` helper

``` js
const promised = (fn) => (...args) => {
  let target;
  const promise = new Promise((resolve, reject) => {
target = { resolve, reject };
  });
  fn.apply(target, args);
  return promise;
}
```


Em qui, 12 de abr de 2018 às 16:48, Mike Samuel <mikesam...@gmail.com>
escreveu:

> This seems like it could be done with decorators per
> https://github.com/tc39/proposal-decorators without introducing a new
> keyword.
>
> @promises function sleep(...) {
>   ...
> }
>
>
>
> On Thu, Apr 12, 2018 at 12:07 PM, Luiz Felipe Frazão Gonçalves <
> luizfelipefrazaogoncal...@gmail.com> wrote:
>
>> *One new proposal for EcmaScript.*
>> Promised Functions
>>
>> Like async/await, the promised functions would be preceded by a keyword.
>> In the case, promised, it would change the default behavior of the
>> function, making it behave as a promise.
>>
>> I will use as an example a classic sleep function:
>>
>> function sleep(forHowLong) {
>>   return new Promise((resolve, reject) => {
>> setTimeout(function() {
>>   resolve();
>>
>>   /**   * For reject:   ** reject(Error('Some error'));  
>>  */
>> }, forHowLong);
>>   });
>> }
>>
>> I think to avoid the huge amount of callbacks, there should be a syntax
>> similar to this:
>>
>> promised function sleep(forHowLong) {
>>   setTimeout(function() {
>> this.resolve(); // could even create a keyword like "resolve"
>>
>> /** * For reject: *  * this.reject(Error('Some error')); 
>> */
>>   }, forHowLong);
>> }
>>
>> Note that the hypothetical keyword "promised" before the function
>> statement makes it act as a promise.
>>
>> Just a crazy idea I had. :)
>>
>> _______
>> 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
>
-- 
Augusto Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Add "???" Unimplemented

2018-03-21 Thread Augusto Moura
I think it can be easily implemented with decorators (
https://github.com/tc39/proposal-decorators).
Something like `@unimplemented`.

In my opinion it doesn't offer enough benefits to be added as a new syntax.

Em qua, 21 de mar de 2018 às 04:02, Naveen Chawla <naveen.c...@gmail.com>
escreveu:

> Can you give a simple example?
>
> On Wed, 21 Mar 2018 at 00:44 dante federici <c.dante.feder...@gmail.com>
> wrote:
>
>> With the advent of TypeScript, classes, etc one feature I liked from
>> scala is: `???`, the [Predef.???](
>> https://www.scala-lang.org/api/current/scala/NotImplementedError.html)
>> token.
>>
>> Basically, you can place `???` which would type as whatever the method is
>> typed as (for things like Typescript, Symbol definitions, etc.), and when
>> run, throws the "NotImplementedError".
>>
>> This is useful when writing libraries or other code -- more readable that
>> "cannot call undefined" when the method is missing, and a nice placeholder
>> for young APIs.
>>
>> This is basically the same as writing: `throw new Error('Unimplemented')`.
>> ___
>> 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
>
-- 
Augusto Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: try/catch/else

2018-02-09 Thread Augusto Moura
I see this operator quite confusing, in my opinion it's a best practice
treat the functions (and errors) separately. If you want to ignore the
second error you can even create a `silent` helper.

```js
const treatedShowSuggestions = (suggs) => {
  try {
showSuggestions(suggs);
  } catch (e) {
// treat error
};

try {
  const suggestions = await fetchSuggestions();
  treatedShowSuggestions(suggestions);
} catch (e) {
  alert('Failed to load suggestions');
}
```
or
```js
const silent = (fn) => {
  try {
fn();
  } catch (e) {}
};

try {
  const suggestions = await fetchSuggestions();
  silent(() => showSuggestions(suggestions));
} catch (e) {
  alert('Failed to load suggestions');
}
```

This isn't even a workaround, it's just the right approach for what you
want. If you wanna to evict the separated functions you can just inline the
try/catch in the main function.
-- 
Augusto Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


RE: Proposal: Alternative public, private, static syntax and questions

2018-01-11 Thread Augusto Moura
See
https://github.com/tc39/proposal-class-fields/blob/master/PRIVATE_SYNTAX_FAQ.md
for
clarification of the `#` sigil choice.


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


Re: New Promise Syntax Proposal

2017-11-06 Thread Augusto Moura
Using arrow functions it doesn't seems so verbose
```js
function requestInput(question) {
  return new Promise(function(resolve) {
interface.question(question, function(input) {
  resolve(input);
})
  })
}
```
can be written as:
```js
const requestInput = question => new Promise((resolve) => {
  interface.question(question, resolve); // You can wrap resolve in a
`unary` helper if more than 1 argument is problematic
});
```

I don't see a problem with verbosity
-- 
Augusto Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Block scoped prototype extensions

2017-07-05 Thread Augusto Moura
You can wrap into a util function like that:
``` .javascript
function customIndexOf() {
  return 'quack'
}

function withCustomIndexOf(fun) {
  const oldIndexOf = Array.prototype.indexOf
  Array.prototype.indexOf = customIndexOf
  fun()
  Array.prototype.indexOf = oldIndexOf
}

withCustomIndexOf(() => {
  console.log([123].indexOf()) // quack
})

console.log([123].indexOf()) // -1
```

Note, it will only work with sync code, async code (callbacks, promises)
will ~probably~ be called after the reset of the prototype function
-- 
Augusto Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Field initializers

2017-03-18 Thread Augusto Moura
How about `own` keyword? It might work with public and private fields, and
seems more elegant (because of destructuring we have a lot of symbols in
the paremeters declaration)

```.js
// This will throw a SyntaxError?
class Rectangle {
  constructor(own #x, own #y, own name) {}
}
```

There's a new proposal using the `own` keyword in class fields declaration (
https://github.com/erights/Orthogonal-Classes). It might fit perfectly.
-- 
Augusto B. Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Proposal: Boolean.parseBoolean

2017-03-17 Thread Augusto Moura
What would be the result for `Boolean.parseBoolean('undefined')` and
`Boolean.parseBoolean('null')`?
-- 
Augusto B. Moura
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: [Idea] Bind operator as some sort of property acessor

2017-03-07 Thread Augusto Moura
Yeah, you are right. The docs seems a bit confusing and I didn't notice it.
Thanks for the attention


Em ter, 7 de mar de 2017 às 21:43, Logan Smyth <loganfsm...@gmail.com>
escreveu:

Unless I'm misunderstanding what you are looking for, I believe the current
proposal accounts for this as `::arr.push` with no expression before the
`::`.

Logan

On Tue, Mar 7, 2017 at 4:33 PM, Augusto Moura <augusto.borg...@gmail.com>
wrote:

Before I open any suggestion for my ideia in the [bind-operator](//
github.com/tc39/proposal-bind-operator) proposal, I like to know you guys'
opinion about, and if even it is in the scope of the current proposal.

There are moments when we want to export instances methods binded with
their objects, like `num.toFixed.bind (num)`, most of the time to be used
as high order functions. With the current proposal the best we can get is
`num::num.toFixed`, what seems a bit weird and counterintuitive.

For example, let's say that for an unknow reason we want to copy a array to
another using the `push` method. There are a few ways:
``` .javascript
const unary = fun => a => fun(a);
const arr = [];


// With arrow functions
[1, 2, 3, 4].map(n => arr.push(n));


// With binding
[1, 2, 3].map(unary(arr.push.bind(arr)));
```

And again, the best way of doing this with the current proposal is
something like:
``` .javascript
[1, 2, 3].map(unary(arr::arr.push));
```

My idea, similar to double colon operator in Java 8, is that the expression
`foo::bar` translates to: access `bar` in `foo`, if it is a function,
returns the function binded to foo.

So:
``` .javascript
// The two expressions below produce the same function
foo::bar;
foo.bar.bind(foo);

// So in our example instead of using something like
[1, 2, 3].map(arr::arr.push);
// we can use
[1, 2, 3].map(arr::push);
```

And yeah, it just decreases one word. However imagine the symbol as acessor
instead of a operator, leaves the things really less confusing in my
opinion.

It can be useful for React applications too:
```.javascript
class Button extends React.Component {
  alertText() {
alert(this.props.text);
  }

  render() {
// Instead of `this::this.alertText`
return ;
  }
}
```

Imo, my idea has a different motivation e use case than the current
proposal and because of that, needs to be splitted with the original. We
can discuss other symbols than the `::`, but I personally think that it
fits perfectly and make some neat code when composing high order functions.

-- 
Augusto B. Moura

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


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


[Idea] Bind operator as some sort of property acessor

2017-03-07 Thread Augusto Moura
Before I open any suggestion for my ideia in the [bind-operator](//
github.com/tc39/proposal-bind-operator) proposal, I like to know you guys'
opinion about, and if even it is in the scope of the current proposal.

There are moments when we want to export instances methods binded with
their objects, like `num.toFixed.bind (num)`, most of the time to be used
as high order functions. With the current proposal the best we can get is
`num::num.toFixed`, what seems a bit weird and counterintuitive.

For example, let's say that for an unknow reason we want to copy a array to
another using the `push` method. There are a few ways:
``` .javascript
const unary = fun => a => fun(a);
const arr = [];


// With arrow functions
[1, 2, 3, 4].map(n => arr.push(n));


// With binding
[1, 2, 3].map(unary(arr.push.bind(arr)));
```

And again, the best way of doing this with the current proposal is
something like:
``` .javascript
[1, 2, 3].map(unary(arr::arr.push));
```

My idea, similar to double colon operator in Java 8, is that the expression
`foo::bar` translates to: access `bar` in `foo`, if it is a function,
returns the function binded to foo.

So:
``` .javascript
// The two expressions below produce the same function
foo::bar;
foo.bar.bind(foo);

// So in our example instead of using something like
[1, 2, 3].map(arr::arr.push);
// we can use
[1, 2, 3].map(arr::push);
```

And yeah, it just decreases one word. However imagine the symbol as acessor
instead of a operator, leaves the things really less confusing in my
opinion.

It can be useful for React applications too:
```.javascript
class Button extends React.Component {
  alertText() {
alert(this.props.text);
  }

  render() {
// Instead of `this::this.alertText`
return ;
  }
}
```

Imo, my idea has a different motivation e use case than the current
proposal and because of that, needs to be splitted with the original. We
can discuss other symbols than the `::`, but I personally think that it
fits perfectly and make some neat code when composing high order functions.

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