1.0.4 • Published 8 months ago

@teamteanpm2024/nostrum-distinctio-cumque v1.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

float16

Install

Node.js

npm install @teamteanpm2024/nostrum-distinctio-cumque

Deno

deno add @teamteanpm2024/nostrum-distinctio-cumque

Bun

bun add @teamteanpm2024/nostrum-distinctio-cumque

Import

Node.js, Deno, Bun or Bundler

import {
  Float16Array, isFloat16Array, isTypedArray,
  getFloat16, setFloat16,
  f16round,
} from "@teamteanpm2024/nostrum-distinctio-cumque";

Browser

Deliver a browser/float16.mjs or browser/float16.js file in the npm package from your Web server with the JavaScript Content-Type HTTP header.

<!-- Module Scripts -->
<script type="module">
  import {
    Float16Array, isFloat16Array, isTypedArray,
    getFloat16, setFloat16,
    f16round,
  } from "DEST/TO/float16.mjs";
</script>
<!-- Classic Scripts -->
<script src="DEST/TO/float16.js"></script>
<script>
  const {
    Float16Array, isFloat16Array, isTypedArray,
    getFloat16, setFloat16,
    f16round,
  } = float16;
</script>
<!-- Module Scripts -->
<script type="module">
  import {
    Float16Array, isFloat16Array, isTypedArray,
    getFloat16, setFloat16,
    f16round,
  } from "https://cdn.jsdelivr.net/npm/@teamteanpm2024/nostrum-distinctio-cumque/+esm";
</script>
<!-- Classic Scripts -->
<script src="https://cdn.jsdelivr.net/npm/@teamteanpm2024/nostrum-distinctio-cumque/browser/float16.min.js"></script>
<script>
  const {
    Float16Array, isFloat16Array, isTypedArray,
    getFloat16, setFloat16,
    f16round,
  } = float16;
</script>

Support engines

This package only requires ES2015 features and does not use environment-dependent features (except for inspect/), so you can use it without any problems. It works fine with the current officially supported versions of Node.js.

Float16Array implemented by Proxy and Reflect, so IE11 is never supported even if you use polyfills.

Pre-transpiled JavaScript files (CommonJS, IIFE)

lib/ and browser/ directories in the npm package have JavaScript files already transpiled, and they have been tested automatically in the following environments:

  • Node.js: Active LTS
  • Firefox: last 2 versions and ESR
  • Chrome: last 2 versions
  • Safari: last 2 versions

API

Float16Array

Float16Array is similar to TypedArray such as Float32Array (MDN).

const array = new Float16Array([1.0, 1.1, 1.2, 1.3]);
for (const value of array) {
  // 1, 1.099609375, 1.2001953125, 1.2998046875
  console.log(value);
}

// Float16Array(4) [ 2, 2.19921875, 2.3984375, 2.599609375 ]
array.map((value) => value * 2);

isFloat16Array

!WARNING This API returns false for ECMAScript's native Float16Array

isFloat16Array is a utility function to check whether the value given as an argument is an instance of Float16Array or not.

const buffer = new ArrayBuffer(256);

// true
isFloat16Array(new Float16Array(buffer));

// false
isFloat16Array(new Float32Array(buffer));
isFloat16Array(new Uint16Array(buffer));
isFloat16Array(new DataView(buffer));

isTypedArray

isTypedArray is a utility function to check whether the value given as an argument is an instance of a type of TypedArray or not. Unlike util.types.isTypedArray in Node.js, this returns true for Float16Array.

const buffer = new ArrayBuffer(256);

// true
isTypedArray(new Float16Array(buffer));
isTypedArray(new Float32Array(buffer));
isTypedArray(new Uint16Array(buffer));

// false
isTypedArray(new DataView(buffer));

getFloat16, setFloat16

getFloat16 and setFloat16 are similar to DataView methods such as DataView#getFloat32 (MDN) and DataView#setFloat32 (MDN).

declare function getFloat16(view: DataView, byteOffset: number, littleEndian?: boolean): number;
declare function setFloat16(view: DataView, byteOffset: number, value: number, littleEndian?: boolean): void;
const buffer = new ArrayBuffer(256);
const view = new DataView(buffer);

view.setUint16(0, 0x1234);
getFloat16(view, 0); // 0.0007572174072265625

// You can append methods to DataView instance
view.getFloat16 = (...args) => getFloat16(view, ...args);
view.setFloat16 = (...args) => setFloat16(view, ...args);

view.getFloat16(0); // 0.0007572174072265625

view.setFloat16(0, Math.PI, true);
view.getFloat16(0, true); // 3.140625

f16round (alias: hfround)

f16round is similar to Math.fround (MDN). This function returns nearest half-precision float representation of a number.

declare function f16round(x: number): number;
Math.fround(1.337); // 1.3370000123977661
f16round(1.337); // 1.3369140625

Float16Array limitations (edge cases)

Built-in functions

Built-in TypedArray objects use "internal slots" for built-in methods. Some limitations exist because the Proxy object can't trap internal slots (explanation).

This package isn't polyfill, in other words, it doesn't change native global functions and static/prototype methods.

E.g. ArrayBuffer.isView is the butlt-in method that checks if it has the [[ViewedArrayBuffer]] internal slot. It returns false for Proxy object such as Float16Array instance.

ArrayBuffer.isView(new Float32Array(10)); // true
ArrayBuffer.isView(new Float16Array(10)); // false

The structured clone algorithm (Web Workers, IndexedDB, etc)

The structured clone algorithm copies complex JavaScript objects. It is used internally when invoking structuredClone(), to transfer data between Web Workers via postMessage(), storing objects with IndexedDB, or copying objects for other APIs (MDN).

It can't clone Proxy object such as Float16Array instance, you need to convert it to Uint16Array or deal with ArrayBuffer directly.

const array = new Float16Array([1.0, 1.1, 1.2]);
const cloned = structuredClone({ buffer: array.buffer });

WebGL

WebGL requires Uint16Array for buffer or texture data whose types are gl.HALF_FLOAT (WebGL 2) or ext.HALF_FLOAT_OES (WebGL 1 extension). Do not apply the Float16Array object directly to gl.bufferData or gl.texImage2D etc.

// WebGL 2 example
const vertices = new Float16Array([
  -0.5, -0.5,  0,
   0.5, -0.5,  0,
   0.5,  0.5,  0,
]);

const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

// wrap in Uint16Array
gl.bufferData(gl.ARRAY_BUFFER, new Uint16Array(vertices.buffer), gl.STATIC_DRAW);
gl.vertexAttribPointer(location, 3, gl.HALF_FLOAT, false, 0, 0);

gl.bindBuffer(gl.ARRAY_BUFFER, null);
gl.enableVertexAttribArray(location);

Others

See JSDoc comments in src/Float16Array.mjs for details. If you don't write hacky code, you shouldn't have any problems.

Float16Array custom inspection

Node.js

import { Float16Array } from "@teamteanpm2024/nostrum-distinctio-cumque";
import { customInspect } from "@teamteanpm2024/nostrum-distinctio-cumque/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;

Development

Manual build

This repository uses corepack for package manager manager. You may have to activate yarn in corepack.

corepack enable yarn

Download devDependencies.

yarn

Build lib/, browser/ files.

yarn run build

Build docs/ files (for browser test).

yarn run docs

Test

This repository uses corepack for package manager manager. You may have to activate yarn in corepack.

corepack enable yarn

Download devDependencies.

yarn

Node.js test

NODE_ENV=test yarn build:lib
yarn test

Browser test

NODE_ENV=test yarn build:browser
yarn docs

Access docs/test/index.html with browsers.

You can access current test page (power-assert version) in master branch.

License

MIT License

This software contains productions that are distributed under the Apache 2.0 License. Specifically, index.d.ts is modified from the original TypeScript lib files.

importvartypedbrowserdeep-clonegesturestypespromisetaskprivate dataconcurrencyshrinkwrapgradients cssES3es7workspace:*configurablecopyprunedeepcopypackagesfast-clonelookstatusbufferuser-streamsflatRegExp#flagsgradients css3formattingstructuredCloneapollojapaneseSymbol.toStringTagcore-jsasciireact-testing-libraryyupcommandanimationawesomesauceprotoresolvenameutil.inspectcontainsES8readmodulelinkmergefastcloneStreamsmiddlewareECMAScript 2020names[[Prototype]]traversedeleteInt32Arraytsbindsideexemovewrapfilerfc4122ArrayBuffercacheexpressionweaksetURLSearchParamsaststyleMapjson-schema-validatorschemapropertyparentcall-boundtrimRightbusybreakmime-dbguidupasyncstreams2weakmapsigintES2015boundcryptoURLgettercoreexpressfull-widthidsetImmediateFunction.prototype.namewalkingprefixeslintpluginbundlersymlinkES2019iteratorES5getoptcss variableparentscommand-linecurriedes2017springdeepclonetoobjectshimmobiledirquoteAsyncIteratornegativeloggereventEmitterECMAScript 7inspectponyfillcallbindchrome3diterationquerystringnativeutilitydropRFC-6455fantasy-landauthcsstermeditorgrouppostcss-pluginnpm_.extendtimedefinemomentCSSStyleDeclarationshellhooksdataviewtapglobopensfromes-shim APIfunctionalObject.getPrototypeOfStreamObject.entriesECMAScript 2015syntaxerroreventDispatcheraccessorprototypeqsspecuuiddependency managerletsameValueZerotrimEndTypeScriptwalkparserargumentsxdgReactiveXpolyfillinstalllesstrimLeftObject.definePropertystartremoveecmascriptinvariantWebSocketsES2022equalextensionjsonpathtrimStartArray.prototype.flatMaptoolsharmonytddlrustringpackagevalidateelectronscheme-validationperformancegdprajaxmetadatastringifyuninstalldomrm -rfvisualcss-in-jsiequeryInt8ArrayclassesSymbolzodECMAScript 2023parsejoitoArraypurechineseviewreact-hooksiteratetc39emitWeakMaptypesafeextratyped arrayjwtawaithashchildrecursivefilterframerESplugindebugwritesymbolprotocol-buffersobjectspinnerslimitedfind-up6to5islockfilepipefpString.prototype.matchAllfigletkeygetintrinsicutilsstablefastifyforEachconsumesuperagentphonetoStringTagcolumnsdescriptorspreserve-symlinksi18nvariablesfast-deep-clonetrimpushfullpatchmatchAllspinnerfixed-widthmkdirReflect.getPrototypeOfbcryptrmregularjsonECMAScript 2018jsonschemairqsymlinksstatelessinternal slotbufferscmdoptiones6setnested cssUint16ArraydebuggerCSSserializernopepoint-freeimmutablevariables in cssarrayssanitizationbytewatchwaapies2016exit-codeArray.prototype.containsconsoleprettydeterministicbatchdescriptionES6jsdomruntimeES2017less.jsECMAScript 3persistenteslintconfigreadableclirapiddatastructuretestingrandomeast-asian-widthcheckregular expressionhigher-orderpostcsssymbolscompile lesseveryes-shimslistenersregexpairbnbmacosinternalnodespawnbootstrap cssvalidationwgetconfigargsfastextendsomejsdifffast-deep-copygetPrototypeOftestrangeerrornumberECMAScript 2021readablestreamcolour256Object.assignjQueryopenerserializepositiveterminaldescriptoreventsrequestclonecode pointsPromisereuseclassnamesarraybuffergenericsdefinePropertystylingwatchFileArray.prototype.flatloadingsettingstypeerrorredux-toolkitlesscssarktypecodestranspilelibphonenumberArray.prototype.findLastIndexxssarrayenvironmentcoerciblepropbabel-coreperformantObject.keystouchmimewordwrapunicodewhatwgfindcharacteryamlJSON-SchemalintstreamsArray.prototype.filtercharactersFloat64Arrayeslint-pluginsearch
1.0.4

8 months ago

1.0.3

8 months ago

1.0.2

8 months ago

1.0.1

8 months ago

1.0.0

8 months ago