在 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
<[email protected] <mailto:[email protected]>> 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(<not-falsey>); // 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)
<https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#parseBoolean%28java.lang.String%29>.
Dmitry
_______________________________________________
es-discuss mailing list
[email protected] <mailto:[email protected]>
https://mail.mozilla.org/listinfo/es-discuss
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss