javascript

exercises

exercises.js
/**
 * 6.4 TypedArrays and Binary Data - Exercises
 */

// ============================================
// EXERCISE 1: Basic TypedArray Operations
// ============================================
/**
 * Create a Uint8Array with values 0-255, then:
 * - Find the sum of all values
 * - Find the average
 * - Create a new array with only even numbers
 */
function typedArrayBasics() {
  // Your code here
}

// ============================================
// EXERCISE 2: View the Same Data Differently
// ============================================
/**
 * Create an ArrayBuffer of 8 bytes
 * Set it as two Uint32 values: 0x12345678 and 0xDEADBEEF
 * Then read it as 8 Uint8 values and 4 Uint16 values
 * Return { uint8: [...], uint16: [...] }
 */
function multipleViews() {
  // Your code here
}

// ============================================
// EXERCISE 3: Checksum Calculator
// ============================================
/**
 * Calculate a simple checksum of a byte array:
 * - XOR all bytes together
 * - Return the result as a hex string
 */
function calculateChecksum(bytes) {
  // Your code here
}

// console.log(calculateChecksum(new Uint8Array([0x12, 0x34, 0x56, 0x78])));
// Expected: "52" (0x12 ^ 0x34 ^ 0x56 ^ 0x78 = 0x52)

// ============================================
// EXERCISE 4: Binary String Packer
// ============================================
/**
 * Pack multiple strings into a binary format:
 * [count:4][len1:4][str1][len2:4][str2]...
 * Return the ArrayBuffer
 */
function packStrings(strings) {
  // Your code here
}

/**
 * Unpack strings from the binary format
 */
function unpackStrings(buffer) {
  // Your code here
}

// const packed = packStrings(['Hello', 'World', 'Test']);
// console.log(unpackStrings(packed)); // ['Hello', 'World', 'Test']

// ============================================
// EXERCISE 5: Image Grayscale Converter
// ============================================
/**
 * Convert RGBA pixel data to grayscale
 * Input: Uint8ClampedArray of [R,G,B,A, R,G,B,A, ...]
 * Output: New Uint8ClampedArray with grayscale values
 * Formula: gray = 0.299*R + 0.587*G + 0.114*B
 */
function toGrayscale(imageData) {
  // Your code here
}

// const pixels = new Uint8ClampedArray([255, 0, 0, 255, 0, 255, 0, 255]);
// console.log(toGrayscale(pixels));

// ============================================
// EXERCISE 6: Little/Big Endian Converter
// ============================================
/**
 * Swap endianness of 32-bit integers in a buffer
 */
function swapEndian32(buffer) {
  // Your code here
}

// const buf = new ArrayBuffer(8);
// new Uint32Array(buf).set([0x12345678, 0xDEADBEEF]);
// swapEndian32(buf);
// Should now be: [0x78563412, 0xEFBEADDE]

// ============================================
// EXERCISE 7: Binary Search in Sorted TypedArray
// ============================================
/**
 * Implement binary search for a sorted TypedArray
 * Return index if found, -1 otherwise
 */
function binarySearch(arr, target) {
  // Your code here
}

// const sorted = new Int32Array([1, 3, 5, 7, 9, 11, 13, 15]);
// console.log(binarySearch(sorted, 7));  // 3
// console.log(binarySearch(sorted, 8));  // -1

// ============================================
// EXERCISE 8: Run-Length Encoding
// ============================================
/**
 * Compress bytes using RLE: [value, count, value, count, ...]
 * Only compress runs of 3 or more
 */
function rleEncode(bytes) {
  // Your code here
}

function rleDecode(compressed) {
  // Your code here
}

// const data = new Uint8Array([1, 1, 1, 1, 2, 3, 3, 3, 3, 3]);
// const compressed = rleEncode(data);
// const decompressed = rleDecode(compressed);

// ============================================
// EXERCISE 9: Network Packet Builder
// ============================================
/**
 * Build a network packet with header and payload
 * Header: [version:1][type:1][flags:2][length:4][checksum:4]
 * Return ArrayBuffer containing header + payload
 */
function buildPacket(version, type, flags, payload) {
  // Your code here
}

function parsePacket(buffer) {
  // Your code here
  // Return { version, type, flags, length, checksum, payload }
}

// ============================================
// EXERCISE 10: Bit Manipulation
// ============================================
/**
 * Implement a BitArray class using Uint8Array
 * - constructor(size): create array for 'size' bits
 * - set(index): set bit at index to 1
 * - clear(index): set bit at index to 0
 * - get(index): return bit value at index
 * - toggle(index): flip the bit
 */
class BitArray {
  // Your code here
}

// const bits = new BitArray(32);
// bits.set(0);
// bits.set(7);
// bits.set(31);
// console.log(bits.get(0));   // 1
// console.log(bits.get(1));   // 0
// bits.toggle(0);
// console.log(bits.get(0));   // 0

// ============================================
// EXERCISE 11: Float to Fixed Point
// ============================================
/**
 * Convert Float32Array to 16-bit fixed point (8.8 format)
 * 8 bits for integer part, 8 bits for fractional
 * Return Int16Array
 */
function floatToFixed88(floats) {
  // Your code here
}

function fixed88ToFloat(fixed) {
  // Your code here
}

// const floats = new Float32Array([1.5, 2.25, 3.75, -1.5]);
// const fixed = floatToFixed88(floats);
// const back = fixed88ToFloat(fixed);

// ============================================
// EXERCISE 12: Interleave/Deinterleave
// ============================================
/**
 * Interleave two arrays: [a1,b1,a2,b2,a3,b3...]
 */
function interleave(arr1, arr2) {
  // Your code here
}

/**
 * Deinterleave array: split into two
 */
function deinterleave(arr) {
  // Your code here
}

// const a = new Uint8Array([1, 2, 3, 4]);
// const b = new Uint8Array([10, 20, 30, 40]);
// const interleaved = interleave(a, b);  // [1,10,2,20,3,30,4,40]
// const [c, d] = deinterleave(interleaved);

// ============================================
// SOLUTIONS
// ============================================

/*
// Solution 3
function calculateChecksum(bytes) {
    let checksum = 0;
    for (const byte of bytes) {
        checksum ^= byte;
    }
    return checksum.toString(16).padStart(2, '0');
}

// Solution 7
function binarySearch(arr, target) {
    let left = 0;
    let right = arr.length - 1;
    
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    
    return -1;
}

// Solution 10
class BitArray {
    constructor(size) {
        this.size = size;
        this.bytes = new Uint8Array(Math.ceil(size / 8));
    }
    
    set(index) {
        const byteIndex = Math.floor(index / 8);
        const bitIndex = index % 8;
        this.bytes[byteIndex] |= (1 << bitIndex);
    }
    
    clear(index) {
        const byteIndex = Math.floor(index / 8);
        const bitIndex = index % 8;
        this.bytes[byteIndex] &= ~(1 << bitIndex);
    }
    
    get(index) {
        const byteIndex = Math.floor(index / 8);
        const bitIndex = index % 8;
        return (this.bytes[byteIndex] >> bitIndex) & 1;
    }
    
    toggle(index) {
        const byteIndex = Math.floor(index / 8);
        const bitIndex = index % 8;
        this.bytes[byteIndex] ^= (1 << bitIndex);
    }
}
*/
Exercises - JavaScript Tutorial | DeepML