@selenite/commons
Version:
This typescript package provides a set of frequently used utilities, types and svelte actions for building projects with Typescript and Svelte.
82 lines (81 loc) • 2.3 kB
JavaScript
// eslint-disable-next-line @typescript-eslint/no-namespace
export var Vector2D;
(function (Vector2D) {
Vector2D.Zero = () => ({
x: 0,
y: 0
});
/** Adds two vector2D together. */
Vector2D.add = (a, b) => ({
x: a.x + b.x,
y: a.y + b.y
});
Vector2D.multiply = (a, b) => ({
x: a.x * b,
y: a.y * b
});
Vector2D.divide = (a, b) => ({
x: a.x / b,
y: a.y / b
});
Vector2D.subtract = (a, b) => ({
x: a.x - b.x,
y: a.y - b.y
});
Vector2D.length = (a) => Math.sqrt(a.x ** 2 + a.y ** 2);
Vector2D.normalize = (a) => Vector2D.divide(a, Vector2D.length(a));
Vector2D.distance = (a, b) => Vector2D.length(Vector2D.subtract(a, b));
Vector2D.dot = (a, b) => a.x * b.x + a.y * b.y;
Vector2D.cross = (a, b) => a.x * b.y - a.y * b.x;
Vector2D.angle = (a, b) => Math.acos(Vector2D.dot(a, b) / (Vector2D.length(a) * Vector2D.length(b)));
Vector2D.rotate = (a, angle) => ({
x: a.x * Math.cos(angle) - a.y * Math.sin(angle),
y: a.x * Math.sin(angle) + a.y * Math.cos(angle)
});
})(Vector2D || (Vector2D = {}));
export class Queue {
#inStack = [];
#outStack = [];
constructor(iterable) {
if (iterable)
this.#inStack.push(...iterable);
}
add(e) {
this.#inStack.push(e);
}
peek() {
this.handleEmptyOut("Can't peek, queue is empty.");
return this.#outStack.at(-1);
}
remove() {
this.handleEmptyOut("Can't remove an element, queue is empty.");
return this.#outStack.pop();
}
take(amount) {
const res = [];
for (let i = 0; i < amount; i++) {
res.push(this.remove());
}
return res;
}
takeAll() {
return this.take(this.size);
}
handleEmptyOut(errMsg) {
if (this.#outStack.length === 0) {
this.swapStacks();
}
if (this.#outStack.length === 0) {
throw new Error(errMsg);
}
}
get size() {
return this.#inStack.length + this.#outStack.length;
}
swapStacks() {
const mem = this.#outStack;
this.#outStack = this.#inStack;
this.#inStack = mem;
this.#outStack.reverse();
}
}