Skip to content

Instantly share code, notes, and snippets.

@bxt
Created May 14, 2019 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bxt/195dc7aa45fceebdd1befae3f49f1bdf to your computer and use it in GitHub Desktop.
Save bxt/195dc7aa45fceebdd1befae3f49f1bdf to your computer and use it in GitHub Desktop.
Comparison of Javascript number conversions
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