documentcloud / underscore-contrib

The brass buckles on Underscore's utility belt
MIT License
621 stars 118 forks source link

Boolean helper #254

Open GammaGames opened 1 year ago

GammaGames commented 1 year ago

Pretty frequently I come across the problem of needing to check if an optional variable is true or false. The problem is that the server can send it as true, false, undefined, "true", or "false". I added this mixin (based on this SO answer):

_.mixin({
  isTrue: function(str) {
    return JSON.parse((str || "false").toLowerCase());
  }
});

Thoughts on adding this?

jgonggrijp commented 1 year ago

I'm in favor! Although I would like to slap a !! in front to ensure it always returns a boolean, and call it isTrueish or something like that to clarify that is does not only detect the value true but also string equivalents.

If you submit a pull request that also includes tests and documentation, I will merge it.

GammaGames commented 1 year ago

I wasn't sure where to put it, but since it's primarily dealing with strings that can sometimes be booleans I put it in the string module. Let me know if I messed anything up! :p