Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementation of angular.isBoolean?

I was reviewing some source code and underscore/lodash was included just for the _.isBoolean function. The underscore source is below:

_.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};

Looking at Function components in ng I see similar functions (angular.isObject, angular.isString, angular.isNumber, etc), but no angular.isBoolean function.

The angular.js source has this an internal function (source below), but an issue requesting to make public (feat: register isBoolean as a public member of global angular #5185) was closed saying "other libraries like underscore and lodash solve these problems well".

function isBoolean(value) {
  return typeof value === 'boolean';
}

Questions:

  • My initial reaction was to copy isBoolean and make a named function in my code, but which implementation is more correct?
  • Do I use the underscore version in anticipation of compatibility with a future upgrade?
  • I assume it is a bad idea to "duck punch" my implementation into angular.isBoolean?
like image 421
Kevin Hakanson Avatar asked Jul 02 '14 15:07

Kevin Hakanson


1 Answers

I was reviewing some source code and underscore/lodash was included just for the _.isBoolean function. […] My initial reaction was to convert isBoolean to a local function

Yes, good idea (if you emphasize the just). Maybe not even a function, but simply inline it.

but which implementation is more correct?

They behave differently when objects that are instances of the Boolean class are passed in. Will such ever occur in the app you are reviewing? Probably not. If they do, only you will know whether you want to consider them as booleans.

Apart from that, val === true || val === false has the same effect as typeof val == "boolean".

I assume it is a bad idea to "duck punch" my implementation into angular.isBoolean?

It's unlikely that angular will ever do this, so you hardly will provoke a collision. Still, ask yourself: Is it actually useful there? Will other code use it? For more discussion, have a look at Don't modify objects you don't own.

like image 154
Bergi Avatar answered Sep 29 '22 14:09

Bergi