Last active
December 11, 2015 08:49
-
-
Save jeroenransijn/4575816 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function add() { | |
// Start from zero | |
var total = 0; | |
// Floating-points, bah! | |
// 1e12 = 1000000000000. | |
var factor = 1e12; | |
// Undefined, set in the loop | |
var value; | |
// Something to iterate on | |
var i = arguments.length; | |
// Loop through all the parameters | |
while (i--) { | |
// Multiply by 1e12, to account for peculiarities | |
// of doing addition with floating-point numbers. | |
value = parseFloat(arguments[i]) * factor; | |
// Is it not, not a number? | |
// Then hey, it's a number! | |
if (!isNaN(value)) { | |
total += value; | |
} | |
} | |
// Divide back by 1e12, because we multiplied by | |
// 1e12 to account for floating-point weirdness. | |
return total/factor; | |
} |
This file contains hidden or 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
// can you figure it out? | |
function add() { | |
var args = [].slice.call(arguments), total = 0; | |
for (;args.length; args.shift()) { | |
!args[0] || typeof args[0] === 'boolean' || (total += parseFloat( !(args[0]*1) ? 0 : args[0] ) * 1e12); | |
} | |
return total/1e12; | |
} |
This file contains hidden or 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
// Should equal 15 | |
add(1, 2, 3, 4, 5); | |
// Should equal 0 | |
add(5, null, -5); | |
// Should equal 10 | |
add('1.0', false, 1, true, 1, 'A', 1, 'B', 1, 'C', 1, 'D', 1, 'E', 1, 'F', 1, 'G', 1); | |
// Should equal 0.3, not 0.30000000000000004 | |
add(0.1, 0.2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://coderwall.com/p/kgzygw