Skip to content

Instantly share code, notes, and snippets.

View ArcaneEngineer's full-sized avatar

Nick ArcaneEngineer

View GitHub Profile
@ArcaneEngineer
ArcaneEngineer / fixedpoint.js
Last active April 25, 2024 19:48
Cross-platform deterministic integer division in JavaScript using a tiny WASM include
//Compile the .WAT (WebAssembly text) file to a .WASM binary, put it alongside this .js file, and you're A for Away.
//
//Goodbye to problems working with Javascript's Number, and to the indeterminism of division, remainder and rounding ops across platforms.
//No more need for hefty libraries like BigNumber.js, decimal.js, big.js etc. Great libraries... before WebAssembly came along :)
//
//There is some overhead to crossing the WASM/JS barrier of course. But simplicity and native performance make this more than worthwhile.
//At worst, you can move all your hot logic to WebAssembly to eliminate repeated call-out costs, and in that way you can also avoid
//any further implicit conversions to JavaScript's Number class... at least until you are ready to render the results of your computation.
//Just be careful how you store the values you get back, or conversion back to JS Number is on the cards. I use Int32Array to store them.