3

One of the things I have learned in dealing with Google Closure is that the library has virtually everything I could possibly want in terms of raw data manipulation and management. What's up to me is to build the components on top of it.

Today I was trying to parse a boolean value from a string. I was surprised not to find anything in the Google Closure Library to do this.

Am I supposed to build this myself via the techniques referenced in the question " How can I convert a string to boolean in JavaScript?", or is there another "Google Closure way"™ to parse booleans that I failed to find?

Community
  • 1
  • 1
Technetium
  • 5,902
  • 2
  • 43
  • 54
  • this is a tricky one and you won't find a method for it, consider Boolean('false') == true and Boolean('0') is also true. a custom way is the only way based on your rule set. – lennel Jan 24 '13 at 09:25

2 Answers2

2

Nope, there is no Closure way to do that.

You either follow the advice mentioned in the question you link to, or create your own method that incorporates what string you consider to be true and what false.

thanpolas
  • 848
  • 1
  • 8
  • 20
1

My guess would be the library doesn't include such a function because it's not always typical what you'd expect as accurate (does case matter?). I would probably use goog.string.caseInsensitiveCompare(str, "true") and goog.string.caseInsensitiveCompare(str, "false"), which does exactly what you looking for without any behind-the-scenes magic or room for error.

One interesting note is that goog.string.caseInsensitiveCompare(true, "true") coerces the first argument to a string and therefore returns 0 (for equality). If this is a problem you could use either goog.isString or goog.isBoolean to filter out values ahead of time.

ne8il
  • 2,427
  • 1
  • 20
  • 18