JSFiddle - React, Tailwind, and code Playground

by Jon-Carlos Rivera

HTML

<script src="http://jon-carlos.com/scripts/struct.js"></script>

JavaScript

// Source
var myTestStruct = {
    'foo': 'Uint32', // Alignment = 4
    'bar': 'Uint8Clamped', // Alignment = 1
    'baz': 'Uint16', // Alignment = 2
    'quux': 'Float64' // Alignment = 8
};

//- Formats: * - date, o - hole
//- Packed - each structure is aligned to 64bits and each field is aligned to its data-size
//['********','****','**','*','o']
//- Aligned - both the overall structure and each field is aligned to 64bits
//['********','****','oooo','**','oooooo','*','ooooooo']


// In CPU land, word-aligned structures should be faster. In JS land, who friggan knows.
//	var myAlignedStructure = struct(myTestStruct, true);
//	var testAligned = myAlignedStructure();

var myPackedStructure = struct(myTestStruct);
var testPacked = myPackedStructure();

testPacked.foo = -1000000000; // Should wrap
testPacked.bar = 300; // Should clamp to 255
testPacked.baz = 3500.84 // Should truncate
testPacked.quux = 30543463.3532 // Should perfect

console.log(testPacked.foo, testPacked.bar, testPacked.baz, testPacked.quux);