export interface Vec2 {
  x: number;
  y: number;
}

export function new_v2(x: number, y: number | undefined = undefined): Vec2 {
  y = y || x;
  return { x, y };
}

function vecargs(v: Vec2 | number): Vec2 {
  if (typeof v == "number") {
    return new_v2(v, v);
  } else {
    return v;
  }
}

export function vadd(a: Vec2, b: Vec2 | number): Vec2 {
  b = vecargs(b);
  return { x: a.x + b.x, y: a.y + b.y };
}

export function vsub(a: Vec2, b: Vec2 | number): Vec2 {
  b = vecargs(b);
  return { x: a.x - b.x, y: a.y - b.y };
}

export function vmul(a: Vec2, b: Vec2 | number): Vec2 {
  b = vecargs(b);
  return { x: a.x * b.x, y: a.y * b.y };
}

export function vdiv(a: Vec2, b: Vec2 | number): Vec2 {
  b = vecargs(b);
  return { x: a.x / b.x, y: a.y / b.y };
}

export function vlen(a: Vec2): number {
  return Math.sqrt(a.x * a.x + a.y * a.y);
}

export function vnorm(a: Vec2) {
  const length = vlen(a);
  if (length > 0) {
    a.x /= length;
    a.y /= length;
  }
}
