JSFiddle - React, Tailwind, and code Playground

by Genius

HTML

<div id="test"></div>

JavaScript

function makeRandomArray(length) {
    var data = [];
    for (i=0; i < length; i++) {
        data.push(Math.ceil(Math.random() * 10) -1);
    }
    return data;
}

var timer = {
    startedAt: null,
    stoppedAt: null,
    start: function() {
        this.stoppedAt = null;
        this.startedAt = new Date();
    },
    stop: function() {
        this.stoppedAt = new Date();
    },
    getTime: function() {
        if ( ! this.stoppedAt)
            this.stop();
        
        return this.stoppedAt.getTime() - this.startedAt.getTime();
    }
};

function printData(data, w) {
    var output = '';
    for (var i in data) {
        if (i > 0 && i % w == 0) {
            output += "\n";
        }
        output += data[i];
    }
    $('#test').append($('<pre>'+output+'</pre><br><br>'));
}

// O(n) naive method
function getRect(data, w, x1, y1, x2, y2) {
    var current_y = 0, current_x = 0, output = [];
    for (i = 0; i < data.length; i++) {
        if (i > 0 && i % w == 0) {
            current_y++;
        }
        current_x = i - (current_y * w);
        if (current_y < y2
            && current_y >= y1
            && current_x < x2
            && current_x >= x1) {
           
            output.push(data[i]);
        }
    }
    return output;
}

// Quicker? No, total fail. Array manipulation in JS apparently stinks
function getRectQuicker(data, w, x1, y1, x2, y2) {
    var current_y = 0, output = [];
    
    // Loop through data by ROW
    for (i = 0; i < data.length; i += w) {
        if (current_y < y2 && current_y >= y1) {
            output = output.concat(data.slice(i+x1, i+x2));
        }
        current_y++;
    }
    return output;
}

// Better by ignoring all data before and after section of interest
function getRectQuicker2(data, w, x1, y1, x2, y2) {
    var current_y = 0, current_x = 0, output = [];
    for (i = x1+(w*y1); i < data.length && i < x2+(w*y2); i++) {
        if (i > 0 && i % w == 0) {
            current_y++;
        }
       ...