Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active March 21, 2017 20:10
Show Gist options
  • Save DmitrySoshnikov/5ee1a7d51d8dbe159ae917876b27f36a to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/5ee1a7d51d8dbe159ae917876b27f36a to your computer and use it in GitHub Desktop.
ES proposal: Boolean.parse

Boolean.parse(string)

Specification

Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

When the Boolean.parse function is called with a string argument the following steps are taken:

  1. If Type(string) is not "string"
    • Return false
  2. Let normalizedString be the result of applying String.prototype.toLowerCase on the string
  3. If normalizedString is "true"
    • Return true
  4. Return false

Examples

Boolean.parse('true'); // true
Boolean.parse('false'); // false

// In contrast with problematic:
Boolean('false'); // true

Use-case

Storages which doesn't support actual boolean values at serialization, and only have string-based value types. Example: Node's env arguments.

@claudepache
Copy link

So many issues with a so small proposal:

  1. “If Type(string) is not String, return false” should be “Let string be ? ToString(string)” for consistency with Number.parseInt, Number.parseFloat, Date.parse, JSON.parse, and pretty much every method that expects a string.
  2. Neither JavaScript nor JSON recognises True, TRUE, etc, as a valid variant of true. There is no clear reason to innovate in that regard. Otherwise, one should consider recognising yes.
  3. Another inconsistency: All of Number.parseInt, Number.parseFloat, Date.parse, and JSON.parse ignore leading and trailing spaces, contrarily to the proposed Boolean.parseBoolean.
  4. One can certainly find more useful than false for Boolean.parseBoolean("foo"). For example Number.parseInt, Number.parseFloat and Date.parse return NaN for unrecognised string, and JSON.parse throws an error.

@DmitrySoshnikov
Copy link
Author

DmitrySoshnikov commented Mar 20, 2017

Thanks guys, all are valid points. In the original es-discuss thread, I made truthy/falsey values. Initially Boolean.parseBoolean(1) would result true, and Boolean.parseBoolean(0) would result false. But then reduced it to Java's appropriate Boolean.parseBoolean method.

EDIT: update to Boolean.parse.

@lahmatiy
Copy link

Examples are still using parseBoolean instead of parse

@DmitrySoshnikov
Copy link
Author

@lahmatiy, thanks, fixed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment