Skip to content

Instantly share code, notes, and snippets.

@natanfeitosa
Created August 2, 2024 23:39
Show Gist options
  • Save natanfeitosa/3c3b06e1a81305bbf49b9a3d089a3556 to your computer and use it in GitHub Desktop.
Save natanfeitosa/3c3b06e1a81305bbf49b9a3d089a3556 to your computer and use it in GitHub Desktop.
function stringToNumber(str: string) {
str = str.trim()
if (/[^\d]/.test(str)) {
throw new Error('Deve conter apenas numeros')
}
return Array.from(str).reverse().reduce((acc, cur, idx) => {
let val = (cur.charCodeAt(0) - 48)
return acc + (val * 10 ** idx)
}, 0)
}
console.log(stringToNumber('123456789'))
@natanfeitosa
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment