petamoriken / float16

Stage 3 IEEE 754 half-precision floating-point ponyfill
https://github.com/tc39/proposal-float16array
MIT License
96 stars 7 forks source link

Example does not work, map returns Proxy Object #1081

Open geyang opened 1 year ago

geyang commented 1 year ago

Thanks for this fantastic library!

from the example, the expected output of the following map should be:

    const array = new Float16Array([1.0, 1.1, 1.2, 1.3]);
    const hey = array.map((value) => value);
    console.log(">>>", hey)

Expected Output

>>> [ 2, 2.19921875, 2.3984375, 2.599609375 ]

Actual Output (wrong)

>>> Proxy(Float16Array) {0: 32256, 1: 32256, 2: 32256, 3: 32256, buffer: ArrayBuffer(8), byteLength: 8, byteOffset: 0, length: 4}

This, however, works:

    const array = new Float16Array([1.0, 1.1, 1.2, 1.3]);

    const hey = array.map((value) => console.log(">>>", value ));

Outputs: (correct)

=>>> 2
>>> 2.19921875
>>> 2.400390625
>>> 2.599609375
petamoriken commented 1 year ago

That is a correct behavior since Float16Array proxies Uint16Array by design.

Some JavaScript runtimes can handle the output of console.log, so try custom inspections.

Node.js (Bun):

import { Float16Array } from "@petamoriken/float16";
import { customInspect } from "@petamoriken/float16/inspect";

Float16Array.prototype[Symbol.for("nodejs.util.inspect.custom")] = customInspect;

Deno:

import { Float16Array } from "https://deno.land/x/float16/mod.ts";
import { customInspect } from "https://deno.land/x/float16/inspect.ts";

// deno-lint-ignore no-explicit-any
(Float16Array.prototype as any)[Symbol.for("Deno.customInspect")] = customInspect;