peterolson / BigRational.js

An arbitrary length rational number library for Javascript
The Unlicense
46 stars 15 forks source link

BigRational not deserializable #26

Open ghost opened 8 years ago

ghost commented 8 years ago

I use JSON.stringify to store values in the browser's localStorage (strings only). When I use JSON.parse to get them out of localStorage, they're plain objects, so I have to reinstantiate them as BigRationals.

bigRat(JSON.parse(JSON.stringify(bigRat()))) => Error: Invalid input: too many 'e' tokens

Of course, this is because JSON.stringify stores bigRat as a plain object, without its methods and identity as a bigRat, and the bigRat constructor doesn't accept plain objects.

I'm using toString for this: bigRat(JSON.parse(JSON.stringify(bigRat().toString()))) (which also happens to be more readable in the serialized string), but I think long-term BigRational without toString should be deserializable.

peterolson commented 8 years ago

This seems like two unnecessary steps to me. Why do you need to involve JSON.stringify or JSON.parse here? You can just use bigRat(bigRat().toString())

ghost commented 8 years ago

Sorry, I didn't say that my bigRats are nested in the data I'm serialising (so I'm using the JSON methods on the whole data).

username1565 commented 6 years ago
function parseDecimal(n) {
        var parts = n.split(/e/i);
...

If you add there

console.log(n);

You can see:

[object Object]
Uncaught Error: Invalid input: too many 'e' tokens 

2 e in the string "[object Object]", so you can see this error. function decimal called by function parse(a, b) and a in your case is object. So I did pass this code to the function "parse(a, b)"

    function parse(a, b) {
        if (typeof a === 'object'){
            b = a["denom"] || a["denominator"];
            a = a["num"] || a["numerator"];
        }
       ...another code...

and got success to parse the object:

console.log(bigRat(JSON.parse(JSON.stringify(bigRat("2_1/3")))).toString());

result:

7/3