JSFiddle - React, Tailwind, and code Playground

by darthdeus

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>QUnit Example</title>
  <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.5.0.css">
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="https://code.jquery.com/qunit/qunit-2.5.0.js"></script>
  <script src="tests.js"></script>
</body>
</html>

JavaScript

var Direction = {
    UP: "up",
    DOWN: "down",
    LEFT: "left",
    RIGHT: "right"
};

// A ray is defined by its origin and direction.
function Ray(x, y, dir) {
    this.origin = {
        x: x,
        y: y
    };
    this.direction = dir;
}

// AABB is defined by its top-left corner, width and height.
function AABB(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
}

function compareInterval(value, low, high) {
    // This shouldn't necessarily be required, but it allows us to just specify
    // the bounds of an interval, without checking which of the two is low and which is high.
    if (low > high) {
        var tmp = high;
        high = low;
        low = tmp;
    }

    // And then we simply check if the value lies outside of the interval
    if (value < low) {
        return -1;
    } else if (low <= value && value <= high) {
        return 0;
    } else if (value > high) {
        return 1;
    }
}

function intersect(ray, aabb) {
    switch (ray.direction) {
        case Direction.UP:
        case Direction.DOWN:
        case Direction.LEFT:
        case Direction.RIGHT:
            if (ray.origin.x <= aabb.x) {
                if (compareInterval(ray.origin.y, aabb.y, aabb.y + aabb.h) == 0) {
                    return {
                        x: aabb.x,
                        y: ray.origin.y
                    };
                } else {
                    return null;
                }
            } else {
                return null;
            }
    }
}

QUnit.test("compareInterval", function (assert) {
    assert.equal(compareInterval(-1, 1, 5), -1);
    assert.equal(compareInterval(0, 1, 5), -1);
    assert.equal(compareInterval(0.99, 1, 5), -1);
    assert.equal(compareInterval(2, 1, 5), 0);
    assert.equal(compareInterval(5, 1, 5), 0);
    assert.equal(compareInterval(6, 1, 5), 1);
});

QUnit.test("raycast RIGHT", function (assert) {
    var aabb = new AABB(0, 0, 1, 2);
    // First we test the happy path...