DEV Community

Adam Crockett πŸŒ€
Adam Crockett πŸŒ€

Posted on

The finite uses of Infinity

To my knowledge there a few tricks that you can pull off with Infinity

A number larger than any number is actually pretty useful, as the negative sign and you negative number is then larger than any negative number.

Infinity;
-Infinity;
typeof Infinity; // number
Enter fullscreen mode Exit fullscreen mode
// 1.
"Hello World".substr(4, Infinity);

// 2.
"Hello World".substr(4, -Infinity);
Enter fullscreen mode Exit fullscreen mode

1 outputs o world, usually that's a tiny bit harder, you need to know the length of the string do some bad thing like use an arbitrary large number such as 9e9 although unlikely, it will still fail to account for cases where the string was 9e9 + 1 long, I can't live with that...

2 outputs nothing, because well negative numbers in second position arg of substr

Okay so Infinity is pretty useful for ummm.... Not much let me know what you use it for, I know I have used it from time to time to simplify some problems πŸ”¬

Top comments (3)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

I have used it for sortable NULL values. Do you want it NULLS FIRST or NULLS LAST? Both can be done.

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

Nulls first for sure πŸ₯³

Do you have some code example?

Collapse
 
salarc123 profile image
SalarC123

Infinity can be really useful for implementing dijkstra’s algorithm, except I don’t really know why would would in JavaScript