Last active
January 16, 2017 15:58
-
-
Save jt3k/1870464a53929847a88e2da9c0f48ee4 to your computer and use it in GitHub Desktop.
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
function safeMath(example) { | |
const numbersRegX = /[0-9]+(\.[0-9]+|)?/g; | |
const replaceData = []; | |
example.replace(numbersRegX, function() { | |
replaceData.push(arguments); | |
}); | |
const maxFract = replaceData.reduce((max, [,fract]) => { | |
if (fract && max < fract.length) { | |
max = fract.length; | |
} | |
return max; | |
}, 1); | |
const commonDelimer = `1${'0'.repeat(maxFract)}`; | |
const modifiedExample = example.replace(numbersRegX, function(match) { | |
return `(${match} * ${commonDelimer})`; | |
}); | |
const result = eval(`(${modifiedExample})/${commonDelimer}`); | |
return result; | |
} | |
// example of use | |
safeMath('0.1 + 0.2'); // => 0.3 | |
// bugs: | |
// 2*3 | |
// 2/4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment