Proposal: Boolean.parseBoolean

Michael J. Ryan tracker1 at gmail.com
Tue Mar 21 18:49:59 UTC 2017


I slightly disagree... mainly in that as it stands, we have a fairly loose
type coercion system that allows almost anything to be coerced into a
boolean... in this case "parse" at least in my mind means that it should
cover the most common use cases.   I understand that Boolean("false")
doesn't currently work this way, and why Date.parse doesn't give a date
instance is a bit beyond me.

With my suggested polyfill your use case would work as expected...
However, JS interacts with more than just serialized results from JS.  It
interacts with input from multiple systems, sources, users and good/bad the
content of users.  The type coercion as it exists for boolean is in order
to provide for simplistic validation... why an empty string coerces false,
for example.  Much like we have defined "falsey" values in JS, I think that
Boolean.parse should have common truthy values/strings that can predictably
be converted as a true, where all else is false.

If all it does is:

    input => String(input).toLowerCase() === 'true';

what is the point of extending Boolean?


-- 
Michael J. Ryan - http://tracker1.info

On Mon, Mar 20, 2017 at 10:47 PM, Dmitry Soshnikov <
dmitry.soshnikov at gmail.com> wrote:

> On Mon, Mar 20, 2017 at 4:59 PM, Michael J. Ryan <tracker1 at gmail.com>
> wrote:
>
>> My suggestion for a polyfill.
>>
>> if (!Boolean.parse) {
>>   Boolean.parse = function(input) {
>>     // return false if it is already falsy
>>     if (!input) return false;
>>
>>     var expr = String(input);
>>
>>     // return false if it's reasonably too long of a string
>>     if (expr.length > 10) return false;
>>
>>     // test trimmed input against truthy values
>>     return (/^(-?1|y|t|yes|true)$/).test(expr.trim().toLowerCase());
>>   }
>> }
>>
>> -1/1 are common database boolean/bit fields
>> y/yes also common inputs for truthiness
>> t/true also common for truthiness
>>
>
> Yeah, these might be good in general, although I'd like to reduce the
> proposal to minimum vital version, and JS related. The problem we are
> trying to solve is to parse `"false"` as `false`. It's not possible with
> `Boolean('false')` today. And all the JSON.parse, and regexp manipulations
> are too low-lever implementation details; users want good semantic library!
> :)
>
> So:
>
> ```
> Boolean.parse('true'); // true
> Boolean.parse('false'); // false
> ```
>
> That's all we need for now, and already will be much better semantic
> alternative too all existing "non-semantic building material".
>
> Dmitry
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170321/ba575141/attachment.html>


More information about the es-discuss mailing list