DEV Community

Discussion on: Typescript can be confusing

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Instead of parseInt

['1', '2', '10'].map(x=>~~+x)
Enter fullscreen mode Exit fullscreen mode

Works - and shorter

Collapse
 
tomaszs2 profile image
Tom Smykowski • Edited
Collapse
 
baenencalin profile image
Calin Baenen

The hell did I just read?

Collapse
 
peerreynders profile image
peerreynders
> ['1', '4294967295', '10'].map(x=>~~+x)
(3) [1, -1, 10]
Enter fullscreen mode Exit fullscreen mode

Bitwise NOT (~):

The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). Numbers with more than 32 bits get their most significant bits discarded.

Unsigned right shift (>>>):

Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.

Know the limitations of your tools.

Integers and shift operators in JavaScript

> ['1.1', '9007199254740991.6', '10.9'].map(n => parseInt(n))
(3) [1, 9007199254740991, 10]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️

I know all that, but for the purposes of a simple string -> integer parser, this works just fine

Collapse
 
natelindev profile image
Nathaniel

that works, but unreadable, therefore it's a bad practice, should be ['1', '2', '10'].map(n => Number.parseInt(n));