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.
@ArcaneEngineer
ArcaneEngineer / aos.js
Last active May 31, 2024 16:52
Array-of-struct emulation using TypedArray and some utility functions -- fast, contiguously allocated arrays unlike regular JS arrays of objects.
const systemWordSize = 8; //bytes
const strideLength = 1; //bytes
//...these functions can be optimised to take advantage of 4 or 8 byte reads / writes, depending on system word size.
//Utility functions
function padAndCalcMemberOffsets(type)
{
let structSize = 0;
for (let memberName in type)
@ArcaneEngineer
ArcaneEngineer / array-types-performance-32.js
Last active September 21, 2024 17:34
Array types performance test: regular vs SMI (31-bit) vs Uint32Array
//Ensure we have reproducible read / write sequence via pseudo-random index sequence.
export const MAX_RAND_INT = 4294967296;
export function splitmixUInt32(seed)
{
return function() {
seed |= 0;
seed = seed + 0x9e3779b9 | 0;
let t = seed ^ seed >>> 16;
t = Math.imul(t, 0x21f0aaad);
@ArcaneEngineer
ArcaneEngineer / array-type-performance-32-and-64.js
Last active September 21, 2024 19:03
array-type-performance-32-and-64.js
//Ensure we have reproducible read / write sequence via pseudo-random index sequence.
export const MAX_RAND_INT = 4294967296;
export function splitmixUInt32(seed)
{
return function() {
seed |= 0;
seed = seed + 0x9e3779b9 | 0;
let t = seed ^ seed >>> 16;
t = Math.imul(t, 0x21f0aaad);