@irysius/grid-math
Version:
Tools to assist with grid math and algorithms
114 lines (113 loc) • 3.35 kB
JavaScript
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function checkType(a, b) {
if (a.type == null || b.type == null) {
// Should at least one of the Vector2s be null, default to the opinionated Vector2's type.
return a.type || b.type;
}
else {
if (a.type !== b.type) {
throw new Error(`Tried to operate on two different types of Vector2: ${a.type} & ${b.type}`);
}
return a.type;
}
}
function create(x, y, type) {
let result = { x, y };
if (type != null) {
result.type = type;
}
return result;
}
exports.create = create;
function zero(type) {
let result = { x: 0, y: 0 };
if (type != null) {
result.type = type;
}
return result;
}
exports.zero = zero;
function unit(type) {
let result = { x: 1, y: 1 };
if (type != null) {
result.type = type;
}
return result;
}
exports.unit = unit;
function isVector2(v, typeToCheck) {
return !!(v &&
typeof v.x === 'number' &&
typeof v.y === 'number') &&
(v.type == null || typeof v.type === 'string') &&
(typeof typeToCheck !== 'string' || v.type === typeToCheck);
}
exports.isVector2 = isVector2;
function add(a, b) {
let type = checkType(a, b);
let result = {
x: a.x + b.x,
y: a.y + b.y
};
if (type != null) {
result.type = type;
}
return result;
}
exports.add = add;
function subtract(a, b) {
let type = checkType(a, b);
let result = {
x: a.x - b.x,
y: a.y - b.y
};
if (type != null) {
result.type = type;
}
return result;
}
exports.subtract = subtract;
function multiply(v, k) {
let type = v.type;
let result = {
x: v.x * k,
y: v.y * k
};
if (type != null) {
result.type = type;
}
return result;
}
exports.multiply = multiply;
function negate(v) {
return multiply(v, -1);
}
exports.negate = negate;
function areEqual(a, b, ignoreType) {
return (ignoreType || a.type === b.type) &&
(a.x === b.x && a.y === b.y);
}
exports.areEqual = areEqual;
function closeEnough(e) {
return function areCloseEnough(a, b, ignoreType) {
return (ignoreType || a.type === b.type) &&
(Math.abs(a.x - b.x) < e &&
Math.abs(a.y - b.y) < e);
};
}
exports.closeEnough = closeEnough;
function clone(v) {
return Object.assign({}, v);
}
exports.clone = clone;
});