BigRational.js
BigRational.js copied to clipboard
BigRational not deserializable
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.
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())
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).
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