JSFiddle - React, Tailwind, and code Playground

by KgomDr

JavaScript

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) === 1 ? 1 : 0;
    // if the least significant bit is placed last.
    if (Endianness === "big")
        ret.reverse();
    return ret
}

const bits_to_byte = bits => {
    if (Endianness === "big") {
        bits = bits.slice();
        bits.reverse();
    }
    return Number.parseInt(bits.join(""), 2)
};

class BitArray extends Uint8Array {
    name = "BitArray";

    constructor(param) {
        if (param instanceof Array) {
            const array = new Array(Math.ceil(param.length / 8));
            for (let i = 0; i < param.length; i++)
                array[i] = bits_to_byte(param.slice(i * 8, (i + 1) * 8));
            param = array
        }
        super(param);

        // the Uint8Array that holds the bytes/bits.
        // Object.defineProperty(this, 'bytearray', bytearray);

        const get = (target, prop) => {
            if (typeof prop !== "symbol" && isIntString(prop)) {
                const quotient = ~~(prop / 8);
                const remainder = prop % 8;
                return byte_to_bits(target[quotient])[remainder]
            } else if (prop === "length") {
                return length
            } else {
                return target[prop]
            }
        };

        const set = (target, prop, value) => {
            if (typeof prop !== "symbol" && isIntString(prop)) {
                const quotient = ~~(prop / 8);
                const remainder = prop % 8;
                target[quotient] = target[quotient] | (1 << remainder);
            } else {
                return target[prop] = value;
            }
        }

        return new Proxy(this, {get, set})
    }

    get length() {
        return this.byteLength * 8
    }

    * [Symbol.iterator]() {
        for (let i = 0; i <...