Re: Proposal: Boolean.parseBoolean

2017-03-16 Thread



在 2017/3/17 5:03, Ben Newman 写道:

Just to check my understanding, would

  Boolean.parseBoolean = function (value) {
return !! (value && JSON.parse(String(value)));
  };

be a reasonable polyfill for your proposed function?
This implemention throws for invalid JSON syntax and is case-sensitive 
(Java's counterpart is case-insensitive). Is this better?

```
Boolean.parseBoolean = function (value) {
  return !(!value || /^false$/i.test('' + value));
};
```

However I'm not sure this is widely useful. If the value is not from 
JSON, there are a lot of alternatives for 'true|false', e.g. 'yes|no', 
'on|off', or 'T|F', and different rules for casing/empty value/invalid 
syntax. So it's better to do this in users' code.




This would definitely be useful for parsing `process.env.*` 
environment variables in Node!


Ben

On Thu, Mar 16, 2017 at 4:55 PM Dmitry Soshnikov 
> wrote:


Similar to `Number.parseInt`, the `Boolean.parseBooelan` might be
useful for "boolean strings" retrieved from some string-based
storages, which do not support other types at serialization.

```
Boolean.parseBoolean('true'); // true
Boolean.parseBoolean('false'); // false
```

This is to contrast current:

```
Boolean('false'); // true
```

In JS people do today:

```
let shouldRefresh = (data.shouldRefresh === 'true');
```

Other parsing results:

```
Boolean.parseBoolean('1'); // true
Boolean.parseBoolean(1); // true
Boolean.parseBoolean(); // true
Boolean.parseBoolean(true); // true

// Falsey:
Boolean.parseBoolean('0'); // false
Boolean.parseBoolean(''); // false
Boolean.parseBoolean(false); // false
```

The API, and the results are from Java's corresponding
`Boolean.parseBoolean` method:

https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#parseBoolean(java.lang.String)

.

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



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


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


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

2017-02-24 Thread


在 2017/2/24 20:08, Claude Pache 写道:

Le 24 févr. 2017 à 04:50, 段垚 <duan...@ustc.edu> a écrit :

Hi,


Converting an arbitray value to a number in JS can be rather inconsistent and 
unexpected:

* `null` and `undefined` are different: `+null === 0` but `+undefined` is NaN.

* Empty string and non-nubmeric strings are different: `+"" === 0` but `+"foo"` 
is NaN.


This problem can be worse because JSON only support finite numbers:

```

var total = 0;

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

total === 0; //Oops, NaN is serialized as null, and then converted to 0

```

So I propose a more consistent and stricter number converting function: 
`Number.of(value)`:

1. If `value` is `null` or `undefined`, return `NaN`;

2. If `value` is a number, return `value` itself;

3. If `value.valueOf()` returns a number, return that number, otherwise return 
`NaN`.


This means all non-number values except those have number type `.valueOf()` 
would be converted to NaN:


```

Number.of(null); // NaN

Number.of(''); //NaN

Number.of('1'); //NaN


var total = 0;

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

total; // NaN

```


What do you think?


Regards,

Duan, Yao



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

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


What I actually want is a function/operator that protect against 
non-number values, including strings that can be parsed as numbers,
and objects whose `.toString()` happen to return strings can be parsed 
as numbers.




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

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

In your JSON example:

```js
var total = 0;

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

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


The null-coalescing operator `??` is awosome and will solve my null/undefined 
issue.
However, it seems there is little progress since it was proposed ( 
https://esdiscuss.org/topic/proposal-for-a-null-coalescing-operator ).
Are there objections or simply lack of interest?



—Claude



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


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

2017-02-23 Thread

Hi,


Converting an arbitray value to a number in JS can be rather 
inconsistent and unexpected:


* `null` and `undefined` are different: `+null === 0` but `+undefined` 
is NaN.


* Empty string and non-nubmeric strings are different: `+"" === 0` but 
`+"foo"` is NaN.



This problem can be worse because JSON only support finite numbers:

```

var total = 0;

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

total === 0; //Oops, NaN is serialized as null, and then converted to 0

```

So I propose a more consistent and stricter number converting function: 
`Number.of(value)`:


1. If `value` is `null` or `undefined`, return `NaN`;

2. If `value` is a number, return `value` itself;

3. If `value.valueOf()` returns a number, return that number, otherwise 
return `NaN`.



This means all non-number values except those have number type 
`.valueOf()` would be converted to NaN:



```

Number.of(null); // NaN

Number.of(''); //NaN

Number.of('1'); //NaN


var total = 0;

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

total; // NaN

```


What do you think?


Regards,

Duan, Yao



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


Re: Add an option to omit prototype of objects created by JSON.parse()?

2016-10-01 Thread

One of the explanations:

"The pitfalls of using objects as maps in JavaScript" 
http://www.2ality.com/2012/01/objects-as-maps.html



在 2016/10/1 21:19, Bob Myers 写道:
What is the problem with the object resulting from `JSON.parse` having 
a prototype again?



On Sat, Oct 1, 2016 at 12:57 PM, 段垚 <duan...@ustc.edu 
<mailto:duan...@ustc.edu>> wrote:


I thought my original mail did not reach es-discuss and re-sent it.

Please refer to

https://esdiscuss.org/topic/proposal-add-an-option-to-omit-prototype-of-objects-created-by-json-parse

<https://esdiscuss.org/topic/proposal-add-an-option-to-omit-prototype-of-objects-created-by-json-parse>


It seems the overhead of creating a prototypeless copy is
significant, and `Object.getOwnPropertyDescriptors(v)` creates
even more objects.


在 2016/10/1 11:19, Jordan Harband 写道:

```
JSON.parse(str, (k, b) => {
if (v && typeof v === 'object' && !Array.isArray(v)) {
return Object.create(null, Object.getOwnPropertyDescriptors(v));
  }
  return v;
});
    ```

On Mon, Sep 19, 2016 at 1:13 AM, 段垚 <duan...@ustc.edu
<mailto:duan...@ustc.edu>> wrote:

Hi,

It is usually a bad practice to let a map object (an plain
object used as a key-value map) have a prototype.

Objects created by JSON.parse() have a prototype by default,
and we can get rid of them by:


JSON.parse(str, function(k, v) {

if (v && typeof v === 'object' && !Array.isArray(v)) {

   v.__proto__ = null;

}

return v;

});


However, implementors warn that mutating prototype causes
"performance hazards" [1].

How about adding an option to omit prototype of objects
created by JSON.parse()?

E.g.:


JSON.parse(str, { noPrototype: true });


[1]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/The_performance_hazards_of__%5B%5BPrototype%5D%5D_mutation

<https://developer.mozilla.org/en-US/docs/Web/JavaScript/The_performance_hazards_of__%5B%5BPrototype%5D%5D_mutation>


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





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




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


Re: Add an option to omit prototype of objects created by JSON.parse()?

2016-10-01 Thread

I thought my original mail did not reach es-discuss and re-sent it.

Please refer to 
https://esdiscuss.org/topic/proposal-add-an-option-to-omit-prototype-of-objects-created-by-json-parse 



It seems the overhead of creating a prototypeless copy is significant, 
and `Object.getOwnPropertyDescriptors(v)` creates even more objects.



在 2016/10/1 11:19, Jordan Harband 写道:

```
JSON.parse(str, (k, b) => {
if (v && typeof v === 'object' && !Array.isArray(v)) {
return Object.create(null, Object.getOwnPropertyDescriptors(v));
  }
  return v;
});
```

On Mon, Sep 19, 2016 at 1:13 AM, 段垚 <duan...@ustc.edu 
<mailto:duan...@ustc.edu>> wrote:


Hi,

It is usually a bad practice to let a map object (an plain object
used as a key-value map) have a prototype.

Objects created by JSON.parse() have a prototype by default, and
we can get rid of them by:


JSON.parse(str, function(k, v) {

if (v && typeof v === 'object' && !Array.isArray(v)) {

   v.__proto__ = null;

}

return v;

});


However, implementors warn that mutating prototype causes
"performance hazards" [1].

How about adding an option to omit prototype of objects created by
JSON.parse()?

E.g.:


JSON.parse(str, { noPrototype: true });


[1]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/The_performance_hazards_of__%5B%5BPrototype%5D%5D_mutation

<https://developer.mozilla.org/en-US/docs/Web/JavaScript/The_performance_hazards_of__%5B%5BPrototype%5D%5D_mutation>


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




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


Add an option to omit prototype of objects created by JSON.parse()?

2016-09-30 Thread

Hi,

It is usually a bad practice to let a map object (an plain object used 
as a key-value map) have a prototype.


Objects created by JSON.parse() have a prototype by default, and we can 
get rid of them by:



JSON.parse(str, function(k, v) {

if (v && typeof v === 'object' && !Array.isArray(v)) {

   v.__proto__ = null;

}

return v;

});


However, implementors warn that mutating prototype causes "performance 
hazards" [1].


How about adding an option to omit prototype of objects created by 
JSON.parse()?


E.g.:


JSON.parse(str, { noPrototype: true });


[1] 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/The_performance_hazards_of__%5B%5BPrototype%5D%5D_mutation



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


Re: Proposal: add an option to omit prototype of objects created by JSON.parse()

2016-09-28 Thread

在 2016/9/28 22:59, Danielle McLean 写道:


From: 段垚 (mailto:duan...@ustc.edu)
Date: 28 September 2016 at 16:36:52


[I]mplementors warn that mutating prototype causes "performance
hazards".

You don't actually need to mutate any prototypes to get prototypeless
objects out of `JSON.parse` - the reviver function is allowed to
return a new object instead, so you can create a fresh one with the
correct prototype. For example:

```js
JSON.parse(string, function(k, v) {
   if (v && typeof v === 'object' && !Array.isArray(v)) {
 return Object.assign(Object.create(null), v);
   }
   return v;
});
```


Yes, but creating a copy also has performance penalty. This proposal is made 
for performance.


How about adding an option to omit prototype of objects created by
JSON.parse()?

JSON.parse(str, { noPrototype: true });

While you can achieve the appropriate result already without extra
language support, I think this particular situation is common enough
that such an option might be a good idea.

How would you expect this new parameter to interact with the existing
second parameter to `JSON.parse`, the reviver function? I'd suggest
that the cleanest way to add the options would be for the second
parameter to be either an object or function, like this:

```js
JSON.parse(str, someFunc);
// equivalent to
JSON.parse(str, {reviver: someFunc});
```

Looks reasonable.

Maybe we can simply add another method, say 
`JSON.parseWithoutPrototype()`. This makes feature detection easier.



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


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

2016-09-28 Thread

在 2016/9/28 14:42, Claude Pache 写道:



Le 28 sept. 2016 à 07:38, 段垚 <duan...@ustc.edu 
<mailto:duan...@ustc.edu>> a écrit :


Because `foo.bar` is equivlant to `foo['bar']` in JS so far, and 
`array.-1` could break this consistency.



On the other hand, `array.first()` seems not necessary because 
`array[0]` is even more handy; `array.last()` looks fine to me.



If someone prefer a more general solution, I recommand `array.get(n)`:

  * if n >= 0 && n < array.length: equivlant to array[n]
  * if n < 0 && -n < array.length: equivlant to array[array.length + n]
  * if n <= -array.length || n >= array.length: throw or return undefined
  * if n is not a integer or not a number: throw or return undefined

The last 2 rules make `array.get(n)` less error prone than 
`array[n]`. I prefer throwing, but maybe returning undefined is more 
JS-style?


For consistency with the rest of the builtin library, `array.get(n)` 
should be equivalent to `array.slice(n)[0]`, which means: convert `n` 
to an integer, and: return `undefined` for out-of-bound index.
I regard such converting behavior a bad legacy of JS, and want to avoid 
it in new APIs.




—Claude



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


Proposal: add an option to omit prototype of objects created by JSON.parse()

2016-09-28 Thread
It is usually a bad practice to let a map-like object (an plain object 
used as a key-value map) have a prototype.


Objects created by JSON.parse() have a prototype by default, and we can 
get rid of them by:



JSON.parse(str, function(k, v) {

 if (v && typeof v === 'object' && !Array.isArray(v)) {

v.__proto__ = null;

 }

 return v;

});


However, implementors warn that mutating prototype causes "performance 
hazards" [1].


How about adding an option to omit prototype of objects created by 
JSON.parse()?


E.g.:


JSON.parse(str, { noPrototype: true });


[1] 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/The_performance_hazards_of__%5B%5BPrototype%5D%5D_mutation



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


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

2016-09-27 Thread
Because `foo.bar` is equivlant to `foo['bar']` in JS so far, and 
`array.-1` could break this consistency.



On the other hand, `array.first()` seems not necessary because 
`array[0]` is even more handy; `array.last()` looks fine to me.



If someone prefer a more general solution, I recommand `array.get(n)`:

  * if n >= 0 && n < array.length: equivlant to array[n]
  * if n < 0 && -n < array.length: equivlant to array[array.length + n]
  * if n <= -array.length || n >= array.length: throw or return undefined
  * if n is not a integer or not a number: throw or return undefined

The last 2 rules make `array.get(n)` less error prone than `array[n]`. I 
prefer throwing, but maybe returning undefined is more JS-style?


在 2016/9/27 20:38, Bob Myers 写道:

This is well-traveled territory.

Whatever is or is not implemented, interfaces which have optional 
arguments and return scalars in one case and arrays in another case 
are a horrible idea.


To my knowledge no-one has ever explained why the following is a bad idea:

```
array.0
array.-1
```

Bob

On Tue, Sep 27, 2016 at 5:42 PM, Nicu Micleusanu > wrote:


I propose to standardize `Array.prototype.first()` and
`Array.prototype.last()`, very similar to underscore `_.first()`
and `_.last()`.


A very basic implementation:

```js

Array.prototype.first = function (n) {

if (!arguments.length) {

return this[0];

} else {

return this.slice(0, Math.max(0, n));

}

};


Array.prototype.last = function (n) {

if (!arguments.length) {

return this[this.length - 1];

} else {

return this.slice(Math.max(0, this.length - n));

}

};

```

___
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: Additional methods for Objects (like Arrays)

2016-01-29 Thread

在 2016/1/30 7:07, Kaustubh Karkare 写道:
I have recently come to feel the need for Object.map, which is like 
Array.map,

except that it receive keys instead of indices.

Object.prototype.map = function(mapFn, context) {
  return Object.keys(this)
.reduce(function(result, key) {
  result[key] = mapFn.call(context, this[key], key, this);
  return result;
}, {});
};

Without this, I frequently do the exact same thing as the above manually,
which leads to unnecessary code duplication.

Given that, it might make sense to match other methods from 
Array.prototype


Object.map
Object.filter
Object.every
Object.some
Object.reduce
Object.find
Object.findKey // like Array.findIndex

Note that wherever applicable, the ordering is non-deterministic.

I'd rather add them as static methods of Object, e.g.

var result = Object.map(obj, function(value, key) { ... });

Because when I use an object as a map, I usually create it without 
prototype (Object.create(null)),

to avoid unintentional access of properties on Object.prototype.





___
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