3 ms·
> You can write isNumber(foo) instead of typeof foo === "number". Indeed you can, but it depends what isNumber does. This is more like what it should do IMO:
by unstable 2y ago
> You can write isNumber(foo) instead of typeof foo === "number".
Indeed you can, but it depends what isNumber does. This is more like what it should do IMO:
function isNumber( foo ) {
return (
(typeof foo === "number") && (foo == foo)) ||
((typeof foo === 'object') && (foo instanceof Number)
);
}
And that is I think the value of micro libs, at least in JS, you don't want to think about all the edge cases when you only want to check if something is a Number.
- layer8 2y agoThis is an argument for having a library that provides that function, but it is not an argument that it should be a micro-library.
- IshKebab 2y agoDoesn't that exclude NaN (which you probably want despite the name)? I think this really highlights that you probably do want to think about those edge cases... In any case this is a bad example because Typescript exists.
- unstable 2y agoAccepting NaN as a number can potentially crash your app, that's why I reject it in isNumber. I only tried to highlight some edge cases that I personally don't like to spend energy on, trying to get it right, when writing code. Btw, isNumber is a dynamic call in the example and unrelated to TypeScript. TypeScript doesn't exist at runtime.
- ristos 2y agoReminds me of the 2ality blog post on that: https://2ality.com/2017/08/type-right.html https://2ality.com/2017/08/type-right.html
- crabmusket 2y agoThis library is a hilarious example of a huge problem with this kind of package. "Number" is in the eye of the beholder. A string containing numeric characters is, in my view, in no useful way "a number". A package that treats it as such just perpetuates weakly-typed nonsense.* But the broader point is, you can't outsource understanding to a package. There will be places in your code where NaN is a perfectly valid number, or Infinity. And other places where you absolutely need to be sure neither of the above make their way in. By pretending that a package can capture the universal essence of "numberless", and that this will broadly apply across the entire JS ecosystem (see reported benefits like "different libraries can all rely on is-number instead of rewriting duplicated helper functions!") is naive. I wrote more about this in a post linked in a top level comment. The is-promise library is another great example. * Personal pet theory is that the package author would have been embarrassed to publish a 1-line package, so included "numeric strings are numbers" as a fig leaf to justify the package's existence. They should have instead created two new packages, is-actual-number and is-numeric-string, so the implementation of is-number could be nice and clean: module.exports = function(n) { return require('is-actual-number')(n) || require('is-numeric-string')(n); } I can feel the power of webscale coursing through me