Proposal: Boolean.parseBoolean

Michael J. Ryan tracker1 at gmail.com
Mon Mar 20 23:59:34 UTC 2017


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

These account for pretty much every case of truthy stored values I've seen
in the wild.

--- Dmitry, sorry, meant to reply-all the first time, also refactored the
polyfill slightly to better account for potentially too long an input value.


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

On Mon, Mar 20, 2017 at 4:41 PM, Michael J. Ryan <tracker1 at gmail.com> wrote:

> I would add case insensitive "t", "y", "yes", 1, -1 as well
>
>
> --
> Michael J. Ryan - tracker1 at gmail.com - http://tracker1.info
>
> Please excuse grammar errors and typos, as this message was sent from my
> phone.
>
> On Mar 20, 2017 11:54 AM, "Dmitry Soshnikov" <dmitry.soshnikov at gmail.com>
> wrote:
>
>> On Thu, Mar 16, 2017 at 1:55 PM, Dmitry Soshnikov <
>> dmitry.soshnikov at gmail.com> 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
>>> ```
>>>
>>>
>> OK, here the actual proposed spec for it: https://gist.github.com/Dmitry
>> Soshnikov/5ee1a7d51d8dbe159ae917876b27f36a
>>
>> I made it plain simple (anything which is not case-insensitive `"true"`
>> is `false`), and copy-pasted from Java.
>>
>> Dmitry
>>
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170320/09964a8c/attachment-0001.html>


More information about the es-discuss mailing list