Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NaN values in Float64Array are incorrectly serialised as null #292

Open
triglav opened this issue Jul 31, 2024 · 2 comments
Open

NaN values in Float64Array are incorrectly serialised as null #292

triglav opened this issue Jul 31, 2024 · 2 comments

Comments

@triglav
Copy link

triglav commented Jul 31, 2024

Float64Array accepts only numbers, null is not a valid value for this type.
Unfortunatelly NaN values within the array are serialised as null, which then naturally comes back after deserialising as 0.
This essentially results in data loss/corruption.

Simple example to reproduce/observe the problem:

const a0 = new Float64Array([NaN, 0, NaN, 1]);
const a1 = stringify(a0);
console.log("a1", a1); // [null,0,null,1]
const a2 = parse<Float64Array>(a1);
console.log("a2", a2); // [0, 0, 0, 1]

const b0 = NaN;
const b1 = stringify(b0);
console.log("b1", b1); // "NaN"
const b2 = parse<number>(b1);
console.log("b2", b2); // NaN
@triglav
Copy link
Author

triglav commented Jul 31, 2024

A quick naive way to fix the problem:

SuperJSON.registerCustom<Float64Array, string>(
    {
        isApplicable: (v): v is Float64Array =>
            Object.prototype.isPrototypeOf.call(Float64Array.prototype, v),
        serialize: v => v.join(","),
        deserialize: v => new Float64Array(v.split(",").map(e => +e)),
    },
    "Float64ArrayCustom"
);

@Mansi1
Copy link

Mansi1 commented Oct 4, 2024

try out my implementation @jsheaven/tjson https://github.com/jsheaven/tjson

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants