JSFiddle - React, Tailwind, and code Playground

by KgomDr

JavaScript

const isString = str => (typeof str === 'string' || str instanceof String);

const isIntString = value => {
    if (/^[-+]?(\d+)$/.test(value))
        return !isNaN(value)
    else
        return false
}

const Endianness = new Uint8Array(new Uint32Array([0x12345678]).buffer)[0] === 0x78 ? "little" : "big";


const byte_to_bits = byte => {
    if (byte > 255 || byte < 0 || isNaN(byte))
        throw new Error("Byte is smaller than 0 or bigger than 255.");
    const ret = new Array(8);
    for (let i = 0; i < 8; i++)
        ret[i] = byte >> i & 1;
    // if the least significant bit is placed last.
    if (Endianness === "big")
        ret.reverse();
    return ret
}

const bits_to_byte = bits => {
    if (bits.length > 8) throw new Error("The bits has to be 8 bits long or shorter.");
    if (Endianness === "little") {
        bits = bits.slice();
        bits.reverse();
    } 
   
    return Number.parseInt(bits.join(""), 2)
};

const get_bit_from_byte = (byte, i) => {
    if (byte > 255 || byte < 0 || isNaN(byte))
        throw new Error("Byte is smaller than 0 or bigger than 255.");
    return byte >> i & 1
}

class BitArray extends Array {
    name = "BitArray";

    constructor(param) {
        let bytearray, length;
        if (param instanceof Array) {
            const array = new Array(Math.ceil(param.length / 8));
            for (let i = 0; i < array.length; i++)
                array[i] = bits_to_byte(param.slice(i * 8, (i + 1) * 8));
            super(param.length);
            length = param.length;
            bytearray = new Uint8Array(array);
        } else {
            bytearray = new Uint8Array(param);
            super(bytearray.length * 8);
            length = bytearray.byteLength * 8;
        }
        // the Uint8Array that holds the bytes/bits.
        Object.defineProperty(this, 'bytearray', bytearray);

        Object.defineProperty(this, 'length', {value: length});

        const get = (target, prop) => {
            if (typeof prop...