Skip to content

Instantly share code, notes, and snippets.

@hdragomir
Last active January 1, 2016 12:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hdragomir/8148600 to your computer and use it in GitHub Desktop.
Save hdragomir/8148600 to your computer and use it in GitHub Desktop.
<script>
function abs(x) {
x = typeof x === "string" ? x.indexOf(',') > -1 ? Number.NaN : ( x.indexOf('.') > -1 ? parseFloat(x, 10) : parseInt(x, 10) ) : (typeof x === "number" || x === null ? x : Number.NaN);
return Number.isNaN(x) ? x : (x === null ? 0 : (x < 0 ? -x : x ));
}
function assert(message, condition) {
condition || console.error(message);
}
assert("-2.5 === 2.5", abs(-2.5) === 2.5);
assert("'2.5' === 2.5", abs("2.5") === 2.5);
assert("asd === NaN", Number.isNaN(abs("asd")));
assert("undefined === NaN", Number.isNaN(abs()));
assert("null === 0", abs(null) === 0);
assert('"2,5" === NaN', Number.isNaN(abs('2,5')));
assert("2e-5 == 2e-5", abs(-2e-5) === 2e-5);
assert("{} === NaN", Number.isNaN(abs({})));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment