Search code examples
javascriptarraysreduceparseint

Converting array of digits to a number


Given the following strings array:

["9", "3", "3", "3", "8", "5", "2", "7", "0", "2", "2", "2", "7", "9", "8", "7"]

I've written this reduce code, trying to convert the array to a number (without using any built in parsers).

d.reduce((res,n,idx)=>{
   res *= 10;
   res += n.charCodeAt(0) - 48;
   console.log(res);
   return res;
},0);

Here is the log:

9
93
933
9333
93338
933385
9333852
93338527
933385270
9333852702
93338527022
933385270222
9333852702227
93338527022279
933385270222798
9333852702227988

933385270222798(8) <-- Should be 7

I've noticed that 9333852702227980 + 7 = 9333852702227988

The code goes of when the number is big, I'm guessing I'm out of safe Integer bounds. How can I fix this?


Solution

  • Look into arbitrary-precision integer arithmetic packages, for example Big Numbers, Big, or Crunch. They should give you some ideas on how to roll your own.