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:
isBoolean
and make a named function in my code, but which implementation is more correct?angular.isBoolean
?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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With