Created
May 14, 2019 16:42
-
-
Save bxt/195dc7aa45fceebdd1befae3f49f1bdf to your computer and use it in GitHub Desktop.
Comparison of Javascript number conversions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const potentialNumbers = [ | |
null, | |
undefined, | |
'', | |
'x', | |
1, | |
1.0, | |
'1', | |
' 1', | |
'1 ', | |
'1.0', | |
'1x', | |
'x1', | |
'1e3', | |
'1.3e-4', | |
'0x4', | |
'0xFF', | |
'032', | |
'09', | |
'NaN', | |
NaN, | |
'-10', | |
'+3', | |
Infinity, | |
'Infinity', | |
]; | |
const converters = { | |
multiply: s => 1 * s, | |
revMultiply: s => s * 1, | |
parseInt: s => parseInt(s), | |
parseInt10: s => parseInt(s, 10), | |
Number: s => Number(s), | |
parseFloat: s => parseFloat(s), | |
unaryPlus: s => +s, | |
floor: s => Math.floor(s), | |
waves: s => ~~s, | |
}; | |
const foo = ( | |
<table> | |
<thead> | |
<tr> | |
<th>input</th> | |
{Object.keys(converters).map(c => ( | |
<th>{c}</th> | |
))} | |
</tr> | |
</thead> | |
<tbody> | |
{potentialNumbers.map(pN => ( | |
<tr> | |
<td> | |
<tt>{JSON.stringify(pN)}</tt> | |
</td> | |
{Object.entries(converters).map(([k, v]) => ( | |
<td>{JSON.stringify(v(pN))}</td> | |
))} | |
</tr> | |
))} | |
</tbody> | |
</table> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment