Clarification for derived promises

2015-07-14 Thread Nicholas C. Zakas

Hi all,

I'm trying to wrap my head around derived promises and wanted to ask for 
a bit of clarification around how `Promise.resolve()` works from a 
derived class. Consider this:


```
class MyPromise extends Promise {}

var p1 = new Promise(function(resolve, reject) {
resolve(42);
});

var p2 = MyPromise.resolve(p1);
p2.then(function(value) {
console.log(value);
});
```

Am I correct in believing that:

1. `p1` is resolved upon being passed to `MyPromise.resolve()`? I 
believe this is what happens in 25.4.4.5 Step 6 
(http://www.ecma-international.org/ecma-262/6.0/#sec-promise.resolve)
2. `p2` is an instance of `MyPromise` that is resolved with a promise 
value of 42.


Thanks!

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: Clarification for derived promises

2015-07-14 Thread Nicholas C. Zakas

Awesome, thank you!

-N

On 7/14/2015 10:12 AM, Domenic Denicola wrote:


Yes.




On Tue, Jul 14, 2015 at 10:10 AM -0700, Nicholas C. Zakas 
standa...@nczconsulting.com mailto:standa...@nczconsulting.com wrote:


Hi all,

I'm trying to wrap my head around derived promises and wanted to ask for
a bit of clarification around how `Promise.resolve()` works from a
derived class. Consider this:

```
class MyPromise extends Promise {}

var p1 = new Promise(function(resolve, reject) {
 resolve(42);
});

var p2 = MyPromise.resolve(p1);
p2.then(function(value) {
 console.log(value);
});
```

Am I correct in believing that:

1. `p1` is resolved upon being passed to `MyPromise.resolve()`? I
believe this is what happens in 25.4.4.5 Step 6
(http://www.ecma-international.org/ecma-262/6.0/#sec-promise.resolve)
2. `p2` is an instance of `MyPromise` that is resolved with a promise
value of 42.

Thanks!

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


--
___
Nicholas C. Zakas
http://www.nczonline.net

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


@@toStringTag spoofing for null and undefined

2015-01-19 Thread Nicholas C. Zakas
According to 19.1.3.6 Object.prototype.toString() [1], it's possible to 
do this:


```js
function Foo(){}

Foo.prototype[Symbol.toStringTag] = Null;

Object.prototype.toString.call(new Foo());   // [object Null]
```

It seems like `Null` and `Undefined` should be added to the step 
17(b) list of exceptions to prevent spoofing of null and undefined 
values using this approach.


I couldn't think of a reason why the current behavior would make sense, 
but if I'm off base, feel free to correct me. :)


[1]: 
https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring


--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Question regarding duplicate __proto__ properties

2014-11-29 Thread Nicholas C. Zakas

In Rev 28, B.3.1 it states:

 *

   It is a Syntax Error
   ifPropertyNameListofPropertyDefinitionListcontains any duplicate
   entries for|__proto__|and at least two of those entries were
   obtained from productions of the
   formPropertyDefinition:PropertyName|:|AssignmentExpression.

I noted that the duplicate name restriction was eliminated back in 
July[1] and was just wondering if __proto__ is indeed a special case?


Thanks.

[1] 
https://github.com/rwaldron/tc39-notes/blob/46d2396e02fd73121b5985d5a0fafbcdbf9c9072/es6/2014-07/jul-29.md#41-review-latest-draft 



--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: Retrieving generator references

2014-11-23 Thread Nicholas C. Zakas
Thanks all. My intent wasn't to propose that something was necessary, 
just to ask if something was available that I was missing. I'll dig in 
on the await spec and take a good look at the various examples everyone 
provided.


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


Retrieving generator references

2014-11-22 Thread Nicholas C. Zakas
After playing around with generators for most of the day (and pretty 
much loving all of it), I ended up with a code example for async that 
looks like this:


```
var fs = require(fs);

var task;

function readConfigFile() {
fs.readFile(config.json, function(err, contents) {
if (err) {
task.throw(err);
} else {
task.next(contents);
}
});
}

function *init() {
var contents = yield readConfigFile();
doSomethingWith(contents);
console.log(Done);
}

task = init();
task.next();
```

The thing that immediately jumped out at me was how poorly the `task` 
variable is being managed. So I was poking around trying to see if there 
was a way to get a reference to the generator instance from within the 
generator itself so I could pass it around, such as:


```
function *init() {
var contents = yield readConfigFile(this);
doSomethingWith(contents);
console.log(Done);
}
```

Of course, `this` isn't a reference to the generator itself, but rather 
the this-binding for the function. It struck me, though, that my example 
could be a lot cleaner if I could get a reference to the generator from 
the generator function and pass that around rather than having to manage 
that reference outside.


Now to my question: is there a way to get a reference to the generator 
from inside the generator function?


(Also, sorry if I'm getting the nomenclature wrong, still trying to wrap 
my head around the relationship between generators, iterators, and 
functions.)


--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: My ECMAScript 7 wishlist

2014-06-06 Thread Nicholas C. Zakas


On 6/5/2014 4:08 PM, Rick Waldron wrote:


* `Object.deepPreventExtensions()`, `Object.deepSeal()`,
`Object.deepFreeze()` - deep versions of
`Object.preventExtensions()`, et al.


Does deep mean that a Map instance's [[MapData]] is frozen if 
deepFreeze is called on a ? eg. what happens here:


var m = Object.deepFreeze(new Map());
m.set(1, 1);

In your blog it mentions the silent failure in non-strict mode, I 
suspect that would still have to apply to these additions for semantic 
consistency.


I wouldn't expect this to apply to [[MapData]] since those are not 
enumerable own properties of the map instance.


* `Object.preventUndeclaredGet()` - change an object's behavior to
throw an error if you try to read from a property that doesn't
exist (instead of returning `undefine`).


This can be achieved with Proxy right, or is that too cumbersome?


It can be done with Proxy, but that kind of sucks because I always need 
to go through the extra step of creating the Proxy for each object and 
passing around the Proxy instead. To me, this is similar to setting a 
property to be readonly in strict mode, except its writeonly (or rather, 
write-first).


--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: My ECMAScript 7 wishlist

2014-06-06 Thread Nicholas C. Zakas


On 6/6/2014 8:38 AM, Mark S. Miller wrote:


But the concern Nicholas raises doesn't seem to have this
property. Reading a property that doesn't exist doesn't carry a
security risk, does it? Object.preventUndeclaredGet doesn't really
protect against anything like ES5 methods did.


That's true, but misses the point I was trying to make. For normal ES 
objects, it is already part of their API contract with their clients 
that the clients can do feature testing to detect the presence or 
absence of a method. The most common way to do such feature testing is 
to get the property and see if it is falsy. (Variations include, 
testing for undefined, testing for undefined or null, and testing if 
its typeof is function.) It's fine if the provider of an abstraction 
does not wish to support this pattern. But it is not ok for one client 
of an object which does support it to prevent that object's other 
clients from successfully using feature detection.


Sorry I was sleeping while most of this conversation was happening. :)

I understand the point about feature detection, it would suck if some 
random code did Object.preventUndeclaredGet() on an object you own and 
were using feature detection on. I still wish for some way to do this 
other than through proxies, but I agree that it would be nice for just 
the object provider to be able to set this behavior.


--
___
Nicholas C. Zakas
http://www.nczonline.net

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


My ECMAScript 7 wishlist

2014-06-05 Thread Nicholas C. Zakas
I wrote this blog post about some of the pain points I'm dealing with 
and dreams of how ES7 might be able to address them:


http://www.nczonline.net/blog/2014/06/03/my-ecmascript-7-wishlist/

A short overview in lieu of posting the whole article here:

* `Array.prototype.first()`, `Array.prototype.last()` - return the first 
and last items, respectively.
* `Array.prototype.isEmpty()` - return true when empty (would also be 
nice on strings, maps, etc.).
* `Function.empty` - a standard empty function that can be used when you 
just want an empty function (IMHO, it indicates intent much better than 
other options toda).
* Custom descriptor attributes - David mentioned this likely will never 
happen, which makes me sad. Maybe the decorators proposal solves this 
use case.
* `Object.deepPreventExtensions()`, `Object.deepSeal()`, 
`Object.deepFreeze()` - deep versions of `Object.preventExtensions()`, 
et al.
* `Object.preventUndeclaredGet()` - change an object's behavior to throw 
an error if you try to read from a property that doesn't exist (instead 
of returning `undefine`).
* Lightweight traits - simple syntax sugar for object literals and 
classes to facilitate mixins.


Further rationale and explanation is in the post. The last three, in 
particular, scratch particular itches I currently have.


**Note:** Please don't take these as formal proposals. If any of the 
ideas seems worthwhile, I'm happy to discuss further and/or put together 
an actual proposal.


Thanks.

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: Using destructuring for function arguments

2014-06-03 Thread Nicholas C. Zakas


On 5/31/2014 1:54 PM, Allen Wirfs-Brock wrote:
What happens here is that none of `secure`, `path`, `domain`, 
`expires` are defined. I can use `typeof` on them to protect against 
this, but then I end up with some lousy looking code:


not really, the thrown exception while processing the arguments should 
terminate the function and you should never start executing the 
function body 


This sounds like there's  a second error in the Firefox implementation. 
If an error should be thrown when the destructured argument is omitted, 
then Firefox is incorrectly continuing to execute the function body.


Am I reading this correctly?



--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Using destructuring for function arguments

2014-05-31 Thread Nicholas C. Zakas
I've been playing around with using destructuring as function arguments 
and have come across some odd behaviors that I'm not sure are 
intentional (or perhaps, not to spec). For context, consider the 
following function:


```
function setCookie(name, value, { secure, path, domain, expires }) {
console.log(secure);
// ...
}

// called as
setCookie(type, js, {
secure: true
});
```

What happens here:
* `secure === true`
* `path === undefined`
* `domain === undefined`
* `expires === undefined`

I'd say all of that behavior is as expected. However, if I omit the 
third argument completely, things get a bit strange:


```
setCookie(type, js);   // throws error at console.log
```

What happens here is that none of `secure`, `path`, `domain`, `expires` 
are defined. I can use `typeof` on them to protect against this, but 
then I end up with some lousy looking code:


```
function setCookie(name, value, { secure, path, domain, expires }) {

if (typeof secure !== undefined) {
// use it
}

if (typeof path !== undefined) {
// use it
}

if (typeof domain !== undefined) {
// use it
}

if (typeof expires !== undefined) {
// use it
}

// ...
}
```

My first thought was that this behavior made sense, since no 
destructuring can happen on undefined. However, the workaround for 
dealing with that behavior seems a bit heavy-handed.


I thought perhaps I could assign a default value, and that would solve 
the problem:


```
function setCookie(name, value, { secure, path, domain, expires } = {}) {
console.log(secure);
// ...
}
```

Unfortunately, that resulted in a syntax error in Firefox. Traceur seems 
to have no problem with it.


So I really have two questions:

1. Who is right about assigning a default value to a destructured 
parameter, Firefox or Traceur?
2. Is the behavior of not having any bindings for destructured parameter 
properties correct? And if so, is it desirable?


Thanks.

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Formalize error.stack?

2013-11-09 Thread Nicholas C. Zakas
Reading through the recent ES draft, I was surprised to see that there 
is no definition for the stack instance property on Error or 
NativeError. This is supported in all browsers (including IE 10+) and 
Node.js, and it seems like it's supported in a reasonably consistent way 
that would lend itself to formal definition.


Is this a spec oversight or is the exclusion intentional?

Thanks.

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: Object.define == Object.mixin??

2012-12-12 Thread Nicholas C. Zakas
I'd vote for replacing duplicate properties by default (as I tend to see 
this as the common case). That being said, the mixin functions I use 
tend to have an optional third argument that let's you change that 
behavior, such as:


// regular
Object.mixin(receiver,supplier);

// safe
Object.mixin(receiver, supplier, true);



-N




On 12/12/2012 11:13 AM, Allen Wirfs-Brock wrote:


On Dec 12, 2012, at 10:10 AM, John J Barton wrote:

On Wed, Dec 12, 2012 at 10:05 AM, Allen Wirfs-Brock 
al...@wirfs-brock.com mailto:al...@wirfs-brock.com wrote:



On Dec 12, 2012, at 9:50 AM, John J Barton wrote:
...
 But most of all we want this feature to land and not just spin
around here.

 jjb

As Object.mixin or as Object.define??

Object.mixin



What should be the effect of trying to mixin a property that already 
exists (as an own property) of the target object.


Object.define(target,src) would presumably have redefined such 
properties using the Object.defineProperty rules. Is that what 
Object.mixin should do.  It could, have different rules.


For example, it could simply replace an existing target property (if 
the existing property is configurable).  Or it could skip existing 
properties or throw an error if a property exists.


Replace is attractive, but it may or may not be what you want for 
accessor properties.  Consider:


var objTarget = {get foo() {/*target*/...}});
Object.mixin(objTarget, {set foo(v) {/*src*/...}});

after the mixin do you want objTarget to look like:
   {set foo(v) {/*src*/...}}   //replace semantics gives you this
or
   {set foo(v) {/*src*/...},
get foo() {/*target*/...} }  //Object.defineProperty semantics 
gives you this


Allen



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


--
___
Nicholas C. Zakas
http://www.nczonline.net

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


[Map|Set|WeakMap].prototype.isEmpty()?

2012-11-02 Thread Nicholas C. Zakas
I had mentioned this in passing in a previous email, but wanted to bring 
it up again.


As I've been playing more with maps and sets, I've come to realize that 
I do this a lot:


//note: FF implementation
if (set.size() === 0) { ... }

Basically, the only thing I've ever done with the size of one of these 
structures is compare it against zero, meaning that I've only ever cared 
if the structure was empty not necessarily how many items were contained 
within.


I don't know if it's worthwhile or not, but I would personally love to 
see isEmpty() as a method on Map, Set, and WeakMap (maybe Array and 
String, too?). It seems to go along nicely with the clear() method on 
Map, Set, and WeakMap.


-N

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: Sets plus JSON

2012-10-04 Thread Nicholas C. Zakas


On 10/3/2012 4:44 PM, Allen Wirfs-Brock wrote:

(oops, forgot to reply-all)

Begin forwarded message:

*From: *Allen Wirfs-Brock al...@wirfs-brock.com 
mailto:al...@wirfs-brock.com

*Date: *October 3, 2012 10:15:57 AM PDT
*To: *Herby Vojc(ík he...@mailbox.sk mailto:he...@mailbox.sk
*Subject: **Re: Sets plus JSON*

This is one of the reasons that it is important that Set (and Map, 
etc.) are specified (and implemented) in a manner that makes them 
fully subclassable.   By subclassing, individual use cases for 
serializing them can be kept distinct rather than multiple libraries 
or subsystems fighting over who gets control of the single 
implementation of Set.prototype.toJSON

That doesn't necessarily preclude a logical default, correct?

-N

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: Sets plus JSON

2012-10-04 Thread Nicholas C. Zakas


On 10/4/2012 11:30 AM, Allen Wirfs-Brock wrote:


On Oct 4, 2012, at 11:02 AM, Nicholas C. Zakas wrote:



On 10/3/2012 4:44 PM, Allen Wirfs-Brock wrote:

(oops, forgot to reply-all)

Begin forwarded message:

*From: *Allen Wirfs-Brock al...@wirfs-brock.com 
mailto:al...@wirfs-brock.com

*Date: *October 3, 2012 10:15:57 AM PDT
*To: *Herby Vojc(ík he...@mailbox.sk mailto:he...@mailbox.sk
*Subject: **Re: Sets plus JSON*

This is one of the reasons that it is important that Set (and Map, 
etc.) are specified (and implemented) in a manner that makes them 
fully subclassable.   By subclassing, individual use cases for 
serializing them can be kept distinct rather than multiple 
libraries or subsystems fighting over who gets control of the 
single implementation of Set.prototype.toJSON

That doesn't necessarily preclude a logical default, correct?

-N


If there is such a thing as a rational default.  And it gets harder to 
define as you move from Set on to Map.


In either case, you are really defining a new application schema layer 
on top of JSON that requires custom deserialization. It won't  be 
meaningful to  JSON clients that don't know your schema conventions. 
 Arguably, having { } as the the default JSON serialization for Set 
and Map serves as a reminder to developers that if they want to use 
JSON to serialize those abstraction they will need to coordinate with 
clients in a deeper way than is required for simple arrays and struct 
like objects.


Allen
I agree, I'm not sure there is a rational default for Map, but I think 
there is one for Set as an array (and it seems like most people agreed).


I don't think that the ability to deserialize should be the deciding 
factor. After all, Date objects are serialized into a string that isn't 
deserialized back into a Date object unless you provide your own reviver.


-N

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Sets plus JSON

2012-10-03 Thread Nicholas C. Zakas
After a little more experimenting with sets (still a really big fan!!), 
I've come across an interesting problem. Basically, I found myself using 
a set and then wanting to convert that into JSON for storage. 
JSON.stringify() run on a set returns {}, because it's an object 
without any enumerable properties. I'm wondering if that's the correct 
behavior because a set is really more like an array than it is an 
object, and perhaps it would be best to define a toJSON() method for 
sets such as:


Set.prototype.toJSON = function() {
return Array.from(this);
};

That way, JSON.stringify() would do something rational by default when 
used with sets.


Thoughts?

Thanks,
Nicholas

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: Sets plus JSON

2012-10-03 Thread Nicholas C. Zakas
So here's a crazy idea (how's that for a lead-in?): What if it were 
possible to specify that you want all non-array JSON objects to be 
revived as maps instead of objects? Perhaps as an option passed to 
JSON.parse()? JSON objects really have no use for prototypes and could 
just as easily be represented as maps. You certainly wouldn't want that 
by default, but as an option, maybe it could make sense.


-N

On 10/3/2012 11:44 AM, Dean Landolt wrote:



On Wed, Oct 3, 2012 at 2:19 PM, Rick Waldron waldron.r...@gmail.com 
mailto:waldron.r...@gmail.com wrote:




On Wed, Oct 3, 2012 at 2:04 PM, Rick Waldron
waldron.r...@gmail.com mailto:waldron.r...@gmail.com wrote:



On Wed, Oct 3, 2012 at 1:43 PM, Brandon Benvie
bran...@brandonbenvie.com mailto:bran...@brandonbenvie.com
wrote:

Another options for Maps is to represent them as an array
of [key, value].


Which is a rough approximation of what a Map looks like
internally.



Sorry, this is incorrect. Map looks more like:

[key1, key2]
[value1, value2]

Sorry for confusion


I image it looking something like [key1, value1, key2, value2...] -- 
index % 2 implies values. Anything more would mean an awful lot of 
unnecessary allocations. I don't see why this wouldn't be sufficient 
for the json form as well, especially if the language had something 
like a take2 iterator.



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


--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: Suggestions for Set

2012-10-02 Thread Nicholas C. Zakas


On 10/1/2012 6:43 PM, Brendan Eich wrote:

Nicholas C. Zakas wrote:
I've been playing around with the Set prototypes in Firefox and 
Chrome (knowing full well that they are incomplete and the spec 
hasn't been finalized yet), and I wanted to share a couple of learnings.


Thanks!

First, since a Set can be initialized with an array, it stands to 
reason that you should be able to easily get an array back from the 
set. However, there is no way to do that right now short of using a 
loop and manually constructing an array. I would really like to see a 
*Set.prototype.toArray* method to easily change the Set back into an 
array. A simple use case would be de-duping an array:


function dedupe(array) {
return (new Set(array)).toArray();
}




Array.from is the way we hope to avoid burdening many iterables with 
toArray methods, as Rick pointed out. Ok?


Better than okay, that's great. Having one way to convert iterables to 
an array makes a lot of sense to me.



Second, the lack of visibility into Sets is problematic. A very 
simple use case is when I want to see if the Set has been initialized 
yet but I can't know what keys might have been used at that point in 
time. Firefox implements a *Set.prototype.size* method which is 
useful to know what I'm dealing with. However, I'm not sure how 
frequently the number of items in the Set actually matters, so a 
*Set.prototype.isEmpty* would be equally useful for this case.


+1 on isEmpty().


:D



Otherwise, I'm finding Sets very useful as a replacement for objects 
that I was using for the same purpose.


Cool. Have you tried Maps for those cases where you want value - 
value mappings?


Not yet, that's next on my list.



/be


--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Suggestions for Set

2012-10-01 Thread Nicholas C. Zakas
I've been playing around with the Set prototypes in Firefox and Chrome 
(knowing full well that they are incomplete and the spec hasn't been 
finalized yet), and I wanted to share a couple of learnings.


First, since a Set can be initialized with an array, it stands to reason 
that you should be able to easily get an array back from the set. 
However, there is no way to do that right now short of using a loop and 
manually constructing an array. I would really like to see a 
*Set.prototype.toArray* method to easily change the Set back into an 
array. A simple use case would be de-duping an array:


   function dedupe(array) {
return (new Set(array)).toArray();
   }


Second, the lack of visibility into Sets is problematic. A very simple 
use case is when I want to see if the Set has been initialized yet but I 
can't know what keys might have been used at that point in time. Firefox 
implements a *Set.prototype.size* method which is useful to know what 
I'm dealing with. However, I'm not sure how frequently the number of 
items in the Set actually matters, so a *Set.prototype.isEmpty* would be 
equally useful for this case.


Otherwise, I'm finding Sets very useful as a replacement for objects 
that I was using for the same purpose.


Thanks,
Nicholas

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Improved Function.prototype.toString in ES6?

2012-08-06 Thread Nicholas C. Zakas
I noticed that there is a proposal to improve how 
Function.prototype.toString works in ES6:

http://wiki.ecmascript.org/doku.php?id=harmony:function_to_string

However, there doesn't seem to be any update in the existing ES6 draft, 
as it says:


   15.3.4.2 Function.prototype.toString ( )

   An implementation-dependent representation of the function is
   returned. This representation has the syntax of a
   FunctionDeclaration. Note in particular that the use and placement
   of white space, line terminators, and semicolons within the
   representation String is implementation-dependent.

   The toString function is not generic; it throws a TypeError
   exception if its this value is not a Function object. Therefore, it
   cannot be transferred to other kinds of objects for use as a method.


Are there going to be a changes to this in ES6?


Thanks,
Nicholas

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Clarification on let/const

2012-07-31 Thread Nicholas C. Zakas

Hi,

I've been going through the spec trying to figure out a few edge cases 
for block bindings. It appears that there is not a functioning demo for 
these (Traceur is mostly working with var semantics, Firefox/Chrome are 
not at all spec-compliant), so just thought I would ask to get a better 
understanding of the expected behavior.


1. If I'm interpreting this correctly, let and const declarations will 
throw an error if used with an identifier that is already defined within 
the same block. So I think that means this should throw an error:


   function f() {
var count = 10;
let count = 20;   // error?
   }


However, it seems like this would not (block variable shadowing function 
variable?):


   function f() {
var count = 10;

if (condition) {
let count = 20;   // no error?
}
   }


And I would assume this is the same (using let instead of var):

   function f() {
let count = 10;

if (condition) {
let count = 20;   // no error?
}
   }

Am I correct in my understanding of these?

2. Since ECMAScript 6 is always running in strict mode, I'm assuming 
that attempting to assign to a declared constant would throw an error 
(in that it behaves similar to a non-writable property in strict mode)?


   const MAX_ITEMS = 30;

   MAX_ITEMS = 25;// error?


Is that correct?


Thanks,
Nicholas

--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: New Object Extension Literal Strawman

2012-05-29 Thread Nicholas C. Zakas
Thanks for the clarifications. I understand wanting to make the 
distinction from an implementer point of view, I'm just not sure that 
developers make the distinction between [[Put]] and 
[[DefineOwnProperty]] even using regular object literals. Is there a 
reason that this:


var obj = {};
obj.{
name: JS
};

Can't act the same as this:

var obj = {};
obj.name = JS;

Wherein, if the property is already defined that acts as [[Put]] and 
otherwise acts as [[DefineOwnProperty]]?


Thanks,
Nicholas

On 5/28/2012 2:27 PM, Allen Wirfs-Brock wrote:

On May 28, 2012, at 1:23 PM, Erik Arvidsson wrote:


On Mon, May 28, 2012 at 12:19 PM, Nicholas C. Zakas
standa...@nczconsulting.com  wrote:

Is it intentional that the first example uses colons between the property
and value while all others use the equals sign?

Yes this is intentional. We discussed this a bit at the F2F meeting
and we came up with the proposal to use = for [[Put]] and : for
[[DefineOwnProperty]]. Having a way to do [[Put]] is important because
it is common to want to trigger setters.

At added a clarification of this to the strawman




For example:

class Monster {
  set health(value) {
this.barColor = value  10 ? 'red' : 'green';
this._health = value;
  }
}

class GiantSpider extends Monster {
  constructor() {
this.{
  health = 100
}
  }
}

If you use .{health: 100} then the setter would not be invoked and the
object would not be in a correct state. This example might be a bit
contrived but using [[DefineOwnProperty]] is not the right answer in a
lot of cases.


This is especially important for setting values of DOM node properties which 
are generally implemented as accessor properties (ie, getters/setters).   That 
is why I used (thanks to dherman) a DOM element in most of the example that use 
+.

Allen





--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: New Object Extension Literal Strawman

2012-05-29 Thread Nicholas C. Zakas

On 5/29/2012 9:45 AM, Brendan Eich wrote:
Note that the modern DOM and WebIDL are being spec'ed so typical DOM 
accessors are on prototypes, so you can't fix the bug by using 
[[Put]] only when the property is own.


There really is a difference between assigning and defining in JS. 
Assigning runs setters, even inherited ones. Defining overrides or 
shadows. EIBTI.
Once again, I'm not debating whether there is or isn't a difference, 
just whether or not that difference is perceivable to regular 
developers. My theory is that it is not, and so you'll end up with a lot 
of code that looks like this:


var element = document.getElementById(myDiv);
element.{
innerHTML: Hello world!,
className: enabled
};

Going by the current definition, this code block would actually have no 
effect because it would be defining new own properties rather than 
assigning values to the existing prototype accessor properties. I cringe 
at the thought of how long it would take most developers to figure out 
that it is the colon that's the problem. IMHO, This code doesn't behave 
as expected.


-N



/be


Thanks,
Nicholas

On 5/28/2012 2:27 PM, Allen Wirfs-Brock wrote:

On May 28, 2012, at 1:23 PM, Erik Arvidsson wrote:


On Mon, May 28, 2012 at 12:19 PM, Nicholas C. Zakas
standa...@nczconsulting.com  wrote:
Is it intentional that the first example uses colons between the 
property

and value while all others use the equals sign?

Yes this is intentional. We discussed this a bit at the F2F meeting
and we came up with the proposal to use = for [[Put]] and : for
[[DefineOwnProperty]]. Having a way to do [[Put]] is important because
it is common to want to trigger setters.

At added a clarification of this to the strawman




For example:

class Monster {
  set health(value) {
this.barColor = value  10 ? 'red' : 'green';
this._health = value;
  }
}

class GiantSpider extends Monster {
  constructor() {
this.{
  health = 100
}
  }
}

If you use .{health: 100} then the setter would not be invoked and the
object would not be in a correct state. This example might be a bit
contrived but using [[DefineOwnProperty]] is not the right answer in a
lot of cases.

This is especially important for setting values of DOM node 
properties which are generally implemented as accessor properties 
(ie, getters/setters).   That is why I used (thanks to dherman) a 
DOM element in most of the example that use +.


Allen







--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: New Object Extension Literal Strawman

2012-05-29 Thread Nicholas C. Zakas



On 5/29/2012 10:56 AM, Allen Wirfs-Brock wrote:

On May 29, 2012, at 10:08 AM, Tab Atkins Jr. wrote:


On Tue, May 29, 2012 at 9:45 AM, Mark S. Millererig...@google.com  wrote:


Language design and extension is a complex process. Being supportive of  multiple use cases generally makes a new 
feature more valuable and more likely to be adopted.  It also makes for smaller, more consistent languages.  Socially, 
support of multiple use cases helps a feature achieve consensus support.   A mustache proposal that only 
allows foo=bar may not do enough to get the support behind it that is needed to make the cut.  Neither 
might a proposal that lacks foo=bar.  The fact that there are multiple perspectives isn't bad, and it 
doesn't mean that we are designing by committee.  It is simply how language design works.
I'm pretty sure that we all understand that this is a complex process. I 
certainly appreciate all of the work that TC 39 puts into the process, 
and appreciate even more that there is transparency in the form of 
strawman proposals. Multiple perspectives are definitely good, and I'm 
just trying to provide another.



Finally, I'm skeptical of any self-styled representation of normal developers that isn't backed 
up with data.  In particular, on this other proposals I generally receive community feedback that 
span all perspectives on the issues. (BTW, on the proposal in question, the positive feedback seems to be 
running quite a bit ahead of the negative). At least some of it seems to come from relatively normal 
programmers (although I have no idea how anybody would actually define that term).  I'm familiar with 
the issues you raise, their general theme is something that we routinely discuss in TC39 (and really in any 
competent language design team).  You really hould assume that we have considered and factored them into our 
proposals.  It is perfectly fair, try to demonstrate why we made the wrong trade-offs in a proposal but this 
will seldom work if you only consider one dimension of the design. Try to be the most comprehensively 
reasoned voice, not the loudest.
As well you should be. What sort of data are you looking for? I'd be 
willing to bet that there wouldn't be a data set that would satisfy your 
parameters. I know that I'm speaking from 15 years of nonstop web 
development experience, at companies both small and large, and have 
worked with people of all skill levels. I definitely have not spent the 
past several years designing JavaScript or evolving it. And even though 
I am 100% sure that you tend to discuss a lot of issues in your meetings 
that we would care about, I don't think it serves anyone if we all 
assume that you all have already thought of everything and understand 
all of the issues.


Tab and I have, IMO, presented our points of view in a very calm, 
measured, rational way. That seems to be in stark contrast to a lot of 
the conversations that happen on this mailing list and others. I would 
hope that such feedback would be welcomed rather than eschewed.




Allen



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


--
___
Nicholas C. Zakas
http://www.nczonline.net


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


Re: Globalization API holiday summary

2011-12-09 Thread Nicholas C. Zakas
I'm still holding out hope for a Locale object that handles everything. 
:) Other than that, I think you have covered everything else.


-N

On 12/8/2011 12:55 PM, Nebojša Ćirić wrote:

6. Ability to set global locale list.

08. децембар 2011. 10.25, Nebojša Ćirić c...@google.com 
mailto:c...@google.com је написао/ла:


There are couple of threads going on and I wanted to wrap up
current state before the holidays...

API:
 1. Use built in toLocaleString family of methods in simple,
functional case*
 2. Use Globalization API as proposed (with some tweaks) for
complex scenarios**

* -
http://wiki.ecmascript.org/doku.php?id=strawman:globalization-integration
** -
http://wiki.ecmascript.org/doku.php?id=globalization:specification_drafts

Proposed changes to the original API:
 1. Remove global namespace *Globalization* (give an internal name
to remove chance of conflicts, i.e. __Globalization).

 2. Use module loading logic instead (we need a way to do a
blocking load of built-in library - *Object.system.load*() is
async at the moment)
  2a. What happens with toLocaleString methods when user doesn't
load @globalization module?

 3. Accept either a String (LDML) or an option Object as a format
parameter in formatters. Simplifies the simple use case and
loading resources from files.
  3a. In addition to DateTimeFormat({year:'long'}) one can
DateTimeFormat().

 4. Come up with the name of the built-in library - *module intl
import '@globalization'* doesn't sound so terrible to me as one
time operation.

 5. Move locale list parameter into the options. I think that
clashes with item 3. where options are being replaced with the
string in some cases. Keeping locales separate removes the conflict.
  5a. Instead of DateTimeFormat(locList, options) have
DateTimeFormat(options), where options hold locale info.

Did I miss anything?

-- 
Nebojša Ćirić





--
Nebojša Ćirić



--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: Globalization API - Sample Use Cases

2011-12-07 Thread Nicholas C. Zakas

On 12/2/2011 1:35 PM, Nebojša Ćirić wrote:
I agree that object literals are more verbose, but they are also more 
readable. I did hear some complains about formatting strings missing 
from the latest spec (we had them before), and mostly from people that 
know how to use them (I still need to look up CLDR docs to write a 
semi complex one).
I agree that object literals are more readable. The price you pay for 
that readability is opacity and many, many characters to get the correct 
behavior. Also, as mentioned before, it makes externalizing 
internationalized settings into a configuration file much more complicated.




The easy solution to that is to add 2 more fields to the options (or 
have them as separate parameter):


1. pattern - as is, I know what I want - MM/yy always generates 9/74 
no matter the locale.
2. skeleton - MM/yy will get you closest matching pattern for a given 
locale.


If pattern or skeleton fields are specified, we ignore the rest of the 
options object.


We had this approach before and removed it from the spec to simplify 
the API, but it shouldn't be hard to get it back in.
I like it. I'd even go one step further to suggest that the first 
argument be allowed as either a string or an object. If a string, then 
treat as a pattern, otherwise, treat as an options object.


-N




02. децембар 2011. 13.28, Nicholas C. Zakas 
standa...@nczconsulting.com mailto:standa...@nczconsulting.com је 
написао/ла:


Instead of continuing with the previous thread, I figured it would
be easier to start a new one.

One of my main points about the current Globalization API is that
the API seems to be designed around complex use cases vs. simple
use cases. Whether intentional or unintentional the Globalization
API fills two gaps in ECMAScript: number formatting and date
formatting. Setting aside the ability to internationalize
currencies and dates, this is a capability that has long been
missing from ECMAScript and developers will rejoice if/when it
arrives.

That being said, I think there's a strong possibility that simple
date/number formatting will end up being a popular use case of the
API as opposed to those who are actively looking for
locale-specific changes due to an internationalized product. I'd
venture a guess to say that the common uses would end up being:

1. Date formatting
2. Number formatting
3. Comparing/sorting (with the current Collator)

I would love it if the ability to format numbers and dates were
simpler than currently spec'ed, more specifically, if the object
literals could be done away with in favor of formatting strings.
Yes, I know formatting strings have some limitations, however the
way I have created internationalized applications in the past has
been by abstracting out the internationalized parts into
configuration files (such as a Java properties file). The data
from that could then be passed into a JS API that Did The Right
Thing. Formatting strings make this trivial, needing to code up an
object literal makes this trickier (JSON is not a great format for
config files).

Just a few extra cents.

-N

___
Nicholas C. Zakas
http://www.nczonline.net
___
es-discuss mailing list
es-discuss@mozilla.org mailto:es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss




--
Nebojša Ćirić



--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Re: Globalization API - Sample Use Cases

2011-12-07 Thread Nicholas C. Zakas

On 12/6/2011 12:48 PM, Nebojša Ćirić wrote:



The easy solution to that is to add 2 more fields to the options
(or have them as separate parameter):

1. pattern - as is, I know what I want - MM/yy always generates
9/74 no matter the locale.
2. skeleton - MM/yy will get you closest matching pattern for a
given locale.

If pattern or skeleton fields are specified, we ignore the rest
of the options object.

We had this approach before and removed it from the spec to
simplify the API, but it shouldn't be hard to get it back in.

I like it. I'd even go one step further to suggest that the first
argument be allowed as either a string or an object. If a string,
then treat as a pattern, otherwise, treat as an options object.

-N


So treat object as a skeleton*, and string as a plain pattern**? That 
may be less confusing, and simple in simple case.


* - implementation picks best appropriate match, uses locale specific 
delimiters, grouping separators...
** - provide formatting as is (as specified by LDML pattern). No 
locale data is used (except some delimiters, say . and , for decimal 
separation).

Precisely.

-N



--
Nebojša Ćirić



--
___
Nicholas C. Zakas
http://www.nczonline.net

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


Globalization API - Sample Use Cases

2011-12-02 Thread Nicholas C. Zakas
Instead of continuing with the previous thread, I figured it would be 
easier to start a new one.


One of my main points about the current Globalization API is that the 
API seems to be designed around complex use cases vs. simple use cases. 
Whether intentional or unintentional the Globalization API fills two 
gaps in ECMAScript: number formatting and date formatting. Setting aside 
the ability to internationalize currencies and dates, this is a 
capability that has long been missing from ECMAScript and developers 
will rejoice if/when it arrives.


That being said, I think there's a strong possibility that simple 
date/number formatting will end up being a popular use case of the API 
as opposed to those who are actively looking for locale-specific changes 
due to an internationalized product. I'd venture a guess to say that the 
common uses would end up being:


1. Date formatting
2. Number formatting
3. Comparing/sorting (with the current Collator)

I would love it if the ability to format numbers and dates were simpler 
than currently spec'ed, more specifically, if the object literals could 
be done away with in favor of formatting strings. Yes, I know formatting 
strings have some limitations, however the way I have created 
internationalized applications in the past has been by abstracting out 
the internationalized parts into configuration files (such as a Java 
properties file). The data from that could then be passed into a JS API 
that Did The Right Thing. Formatting strings make this trivial, needing 
to code up an object literal makes this trickier (JSON is not a great 
format for config files).


Just a few extra cents.

-N

___
Nicholas C. Zakas
http://www.nczonline.net
___
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss


Re: Globalization API Feedback - moar!

2011-11-30 Thread Nicholas C. Zakas

On 11/30/2011 12:01 PM, Brendan Eich wrote:

On Nov 29, 2011, at 1:19 PM, Nicholas C. Zakas wrote:


The reason I started down this path is because the API, as currently designed, 
doesn't fit in with the rest of the JavaScript core language. Just to summarize 
some of my earlier points:

1) No part of core JavaScript uses namespaces today. Having a top-level 
Globalization object that [does] nothing other than provide a hook onto which 
new constructors are placed is a first and doesn't seem very useful. At the 
very least I'd consider killing the Globalization object altogether and just 
let the constructors exist in the global scope.

Injecting new names into the global scope is risky, since all the good names 
are already taking by user-defined globals.

The plan we discussed a few weeks ago was to use a built-in module, which could 
be imported from or declared freely in new opt-in code. Unversioned JS would 
have to use something like the

   Object.system.loadIntrinsic(@globalization)

API-sketch.

Whatever we do, it should be as future-friendly to modules as possible, and it 
shouldn't inject new global names into the shared scope of ES.next and 
unversioned scripts.
To make sure I understand, are you saying that all future ES 
functionality won't introduce new names into the global scope? And 
further, all new functionality would need to be loaded via a module?



2) The current proposal requires that developers maintain a LocaleList object 
and pass that into methods of NumberFormat, DateTimeFormat, and Collator 
(assuming they don't want to use the default). Needing to keep track of an 
object is a pain, but is lessened when that object does everything you need it 
to. That's why I suggested having a Locale object. Yes, you'd need to keep 
track of this object, but at least it would be one object instead of multiple 
objects.

This still seems plausible to me. It caters to Norbert's Customer categories 
1 and 2, if I'm not mistaken.

Which is plausible? The current proposal or my single-object proposal? :)





3) The semantic difference between DateTimeFormat.isSupported(), 
Locale.isSupported(), etc. is minimal. The point I was trying to make is that 
the current requirements for the Globalization API don't preclude having a 
single object. That's simply a design decision, not a huge barrier that can be 
overcome.

Mark's point about isSupported not being binary and simplex is good, 
independent of whether objects are grouped into a Locale or not. Again if I'm 
following correctly (please tell me if not).
Agreed, I was just brainstorming about ways to solve some of the issues 
being brought up. There do seem to be two categories of detection 
necessary for this API, one is binary (is Gregorian calendar supported) 
and one is best fit (what's the closest locale you can approximate).





Again, saying that libraries will handle this is too simple and presumptive. 
You're assuming that some library a) likes what you've done enough to invest in it, b) 
finds some advantage to this API over what it has already, and c) can integrate with what 
they already have. You could create an API that sits unused because libraries don't see 
any advantage to using it vs. what they have already.

Again I agree with you. The flip side is that, per Mark's fine message dated 
November 28, 2011 1:13:24 PM PST, internationalization is multi-state/best-fit 
and complex, with evolving big data, user preferences in the loop.

Doing a low-level built-in library and letting others built higher-level 
abstractions is plausible based on experience with things like canvas, WebGL, 
and typed arrays. We don't get to do the perfect high-level API on short 
notice, certainly not in committee. I'm skeptical we can even do a low-level 
toolkit by next spring, with two truly independent implementations 
interoperating convincingly.

So libraries will handle this is the wrong guiding principle, but let's find the 
high-level sweet spot is high-risk without more time for experimentation and user testing.
I definitely wasn't trying to suggest a truly high-level abstraction, 
but more a mid-level API that has some low-level characteristics and 
some high-level characteristics. Another way to say this is that the API 
makes the simple case simple (hi! I'd just like to format a price for 
display) while allowing more complex cases through other means. I 
present XMLHttpRequest as a good example of a mid-level API, where it's 
easy to do a basic GET request but you can still do fancy things using 
CORS, binary data, HTTP streaming, etc.




I don't have any satisfying answers, but I hope this helps.

/be



-N


On 11/28/2011 4:17 PM, Norbert Lindenberg wrote:

I'm not sure why this discussion is drifting so far in the direction of a functional API. 
I thought objects, constructors, and methods are all part of ECMAScript, are widely used 
in the language specification, in libraries, and in applications, and developers have

Re: Globalization API Feedback - moar!

2011-11-29 Thread Nicholas C. Zakas
 if not.
 */
Locale.isLocaleSupported = function(code){
...
};

/*
 * Replaces supportedLocalesOf
 * @param code The code to check.
 * @return Array of supported locales.
 */
Locale.getSupportedLocales = function(code){
...
};

/*
 * Replaces Globalization.Collator
 * @param a The first item.
 * @param b The second item.
 * @param options (Optional) The options to use when comparing.
 * @return -1 if a comes before b, 0 if they're equal, 1 otherwise
 */
Locale.prototype.compare = function(a, b, options){
...
};

/*
 * Replaces Globalization.NumberFormat
 * @param format A pattern format string for outputting the number.
 * @param value The value to format.
 * @return The number formatted as a string.
 */
 Locale.prototype.formatNumber = function(format, value){
...
};

/*
 * Replaces Globalization.DateFormat
 * @param format A pattern format string for outputting the date.
 * @param value The date to format.
 * @return The number formatted as a string.
 */
Locale.prototype.formatDate = function(format, value){
...
};

You would then be able to create a single Locale instance and have that be used 
in your script. If the constructor is used without an argument, then default 
locale information is used:

var locale = new Locale();

If you provide a code, then that is used:

var locale = new Locale(en-us);

If you provide multiple codes, then the first supported one is used:

var locale = new Locale([en-us, en-gb]);

Then, you can use that locale information for the other operations you want to 
do:

locale.formatDate(DMYs-short, new Date());
locale.formatNumber(##.##, 55);
locale.compare(foo, bar);

By the way, not saying this is the format pattern string that should be used, 
it's just for discussion.

I like having a single object to deal with instead of multiple for everything 
the API is trying to do. It seems a lot more intuitive than needing to manage a 
LocaleList that is passed into new instances of NumberFormat and DateFormat all 
the time (that's a bunch of housekeeping for developers).

Thoughts?

-Nicholas




On 11/21/2011 11:12 AM, Nicholas C. Zakas wrote:
As promised, more verbose feedback for the Globalization API. My general 
feeling is that the API is overly verbose for what it's doing. I'll state my 
bias up front: I'm not a fan of introducing a bunch of new types to handle 
formatting. I'd much rather have additional methods that perform formatting on 
existing objects. My feedback is mostly about eliminating the new constructors 
- which has an added bonus of eliminating the Globalization namespace because 
there would be only one constructor left: Collator.

1. LocaleList

I'm not sure why this type is necessary. I don't believe that locale resolution 
is an expensive operation, and even if it is, I'd expect the implementation to 
cache the results of such resolution for later use. I'd just leave this as an 
internal construct and instruct developers to use arrays all the time.

2. supportedLocalesOf

I find this method name strange - I've read it several times and am still not sure I 
fully understand what it does. Perhaps getSupportedLocales() is a better name 
for this method? (I always prefer methods begin with verbs.)

3. NumberFormat

Number formatting seems simple enough that it could just be added as a series 
of methods on Number.prototype. The three types of formatting (currency, 
decimal, percent) could each have their own method. Currency formatting has 
relatively few options to specify, so it's method can be:

/*
 * Formats the number as if it were currency
 * @param code Currency code, e.g., EUR
 * @param type (Optional) The way to format the currency code, code, 
symbol (default),
 * @param locales - (Optional) Array of locales to use.
 */
Number.prototype.toCurrencyString = function(code, type, locales) {
...
};

var num = 500;
console.log(num.toCurrencyCode(EUR, code));//EUR 500.00


Decimal and percent formatting options are slightly different in that they 
include significant digits options. For that, I prefer to use a formatting 
string rather than the multitude of optional properties as currently defined 
(see http://www.exampledepot.com/egs/java.text/FormatNum.html). The formatting 
string indicates must-have digits as 0 and optional digits as #, allowing you 
to very succinctly specify how you want your number to be output. For example:

/*
 * Formats the number as a decimal string.
 * @param format Format string indicating max/min significant digits
 * @param locales (Optional) Array of locales to use.
 */
Number.prototype.toDecimalString = function(format, locales){
...
};

/*
 * Formats the number as a percent string.
 * @param format Format string indicating max/min

Re: Globalization API: supportedLocalesOf vs. getSupportedLocales

2011-11-29 Thread Nicholas C. Zakas
 Albright; Peter Constable; Shawn Steele
 Cc: es-discuss
 Subject: Re: Globalization API: supportedLocalesOf vs.
getSupportedLocales

 We invented the supportedLocalesOf method to let applications
find out which of its requested locales are supported by the
implementation of a service. A getSupportedLocales function that
simply returns the locales that the implementation actually
supports would be easier to understand, and could also be used by
an application to implement its own locale negotiation. If I
remember correctly, we chose not to offer getSupportedLocales
primarily because the list returned might be huge - possibly over
1000 locales.

 Maybe we should reconsider this? If an application really wants
to have a list of 1000 locales, why not let it have it? If we want
the ability to restrict the list, maybe there can be locale list
as a parameter, and we return only those supported locales for
which a prefix is on the locale list passed in? Or is there a more
fundamental issue with getSupportedLocales?

 Thanks,
 Norbert


 On Nov 21, 2011, at 11:12 , Nicholas C. Zakas wrote:

 2. supportedLocalesOf

 I find this method name strange - I've read it several times
and am still not sure I fully understand what it does. Perhaps
getSupportedLocales() is a better name for this method? (I
always prefer methods begin with verbs.)

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



___
es-discuss mailing list
es-discuss@mozilla.org mailto: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


Globalization API Feedback

2011-11-21 Thread Nicholas C. Zakas
As promised, more verbose feedback for the Globalization API. My general 
feeling is that the API is overly verbose for what it's doing. I'll 
state my bias up front: I'm not a fan of introducing a bunch of new 
types to handle formatting. I'd much rather have additional methods that 
perform formatting on existing objects. My feedback is mostly about 
eliminating the new constructors - which has an added bonus of 
eliminating the Globalization namespace because there would be only one 
constructor left: Collator.


1. LocaleList

I'm not sure why this type is necessary. I don't believe that locale 
resolution is an expensive operation, and even if it is, I'd expect the 
implementation to cache the results of such resolution for later use. 
I'd just leave this as an internal construct and instruct developers to 
use arrays all the time.


2. supportedLocalesOf

I find this method name strange - I've read it several times and am 
still not sure I fully understand what it does. Perhaps 
getSupportedLocales() is a better name for this method? (I always 
prefer methods begin with verbs.)


3. NumberFormat

Number formatting seems simple enough that it could just be added as a 
series of methods on Number.prototype. The three types of formatting 
(currency, decimal, percent) could each have their own method. Currency 
formatting has relatively few options to specify, so it's method can be:


/*
 * Formats the number as if it were currency
 * @param code Currency code, e.g., EUR
 * @param type (Optional) The way to format the currency code, 
code, symbol (default),

 * @param locales - (Optional) Array of locales to use.
 */
Number.prototype.toCurrencyString = function(code, type, locales) {
...
};

var num = 500;
console.log(num.toCurrencyCode(EUR, code));//EUR 500.00


Decimal and percent formatting options are slightly different in that 
they include significant digits options. For that, I prefer to use a 
formatting string rather than the multitude of optional properties as 
currently defined (see 
http://www.exampledepot.com/egs/java.text/FormatNum.html). The 
formatting string indicates must-have digits as 0 and optional digits as 
#, allowing you to very succinctly specify how you want your number to 
be output. For example:


/*
 * Formats the number as a decimal string.
 * @param format Format string indicating max/min significant digits
 * @param locales (Optional) Array of locales to use.
 */
Number.prototype.toDecimalString = function(format, locales){
...
};

/*
 * Formats the number as a percent string.
 * @param format Format string indicating max/min significant digits
 * @param locales (Optional) Array of locales to use.
 */
Number.prototype.toPercentString = function(format, locales){
...
};

var num = 1234.567;
console.log(numtoDecimalString(000##.##)); 01234.57

4. DateTimeFormat

As with NumberFormat, it seems like this could more succinctly be 
implemented as a method on Date.prototype. As its easiest:


/*
 * Format a date
 * @param options The already-defined options for DateTimeFormat
 * @param locales (Optional) Array of locales to use.
 */
Date.prototype.toFormatString = function(options, locales){
...
};

In an ideal world, I'd like to see options overloaded so it can be an 
options object as specified now or a formatting string. I understand 
that there was a sentiment against formatting strings due to their 
limitations and edge case errors. However, I'd like to point out that 
any internationalized web application is highly likely to already be 
using formatting strings for dates, since this is pretty much how every 
other language handles date formatting. That means supporting format 
strings in JavaScript would allow application developers to reuse the 
settings they already have. As it stands now, you'd need to create two 
different ways of formatting dates for a web app: one for your 
server-side language and one for your client-side language (until the 
day everything is running on Node.js, of course). I'd prefer my 
client-side code to reuse settings and configuration that the 
server-side code uses, otherwise I end up with two very different pieces 
of code doing the exact same thing, and there be dragons.


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