All files utils.ts

88.5% Statements 154/174
69.76% Branches 60/86
97.05% Functions 33/34
85.71% Lines 120/140

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 38611x             11x           11x 15727x   15727x         159317x                                     5106708x   11x       15963x 3x   2x   3x     11x       15963x 8x   4x   8x     11x       15963x 134x 66x   134x     11x       15963x 134x 1x   134x     11x         15963x 2x 1x   2x     11x       15963x 15682x 15653x   15682x     433556x     867081x 851118x                 15963x                                 11x 2182x 8x 19x   2174x                   11x 27x 2x 12x   25x 96x             11x               11x 16x 16x 16x 48x 192x 192x       16x 48x 192x   48x 48x 48x 192x     48x 144x 576x         16x 48x 192x   48x 48x 48x 192x         16x 16x 48x     16x   11x           11x                                                                                             11x                                                                     99x         11x                     11x           11x 3x     1x   2x 2x 2x 6x 9x     2x     4940x   11x 4x 4x 4x 4x 4x 4x 4x     11x 2x 2x 2x 2x   2x 6x   2x 2x   2x 2x   2x 2x         2x 2x    
import {DPoint} from './DPoint';
 
interface DGeoInterface {
  DEBUG: boolean;
  parseFormat: string;
}
 
export const DGeo: DGeoInterface = {
  DEBUG: false,
  parseFormat: 'xyz'
};
 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const warn = (...args: any[]): void => {
  if (DGeo.DEBUG) {
    // eslint-disable-next-line no-console
    console.warn(...args);
  }
};
 
// eslint-disable-next-line eqeqeq,@typescript-eslint/no-explicit-any,@typescript-eslint/explicit-module-boundary-types
export const isDefAndNotNull = (a: any): boolean => a != undefined;
 
type CheckFunc = (p: DPoint) => CheckFunction;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type CheckFunc2 = (p: any) => CheckFunction;
 
interface CheckArgument {
  shouldBeDegree: CheckFunc;
  shouldBeMeters: CheckFunc;
  shouldBeInt: CheckFunc;
  shouldBeUInt: CheckFunc;
  shouldBeRadians: CheckFunc;
  shouldExist: CheckFunc2;
}
 
interface CheckFunction {
  checkArgument: (argName: string) => CheckArgument;
}
 
const hook = (scope: CheckFunction): CheckFunc => (): CheckFunction => scope;
 
const shouldBeInt = (
  scope: CheckFunction,
  funcName: string,
  argName: string
): CheckFunc => (p: DPoint): CheckFunction => {
  if (!p.clone().round()
    .equal(p)) {
    warn(`"${funcName}" -> "${argName}" should be Int!`);
  }
  return scope;
};
 
const shouldBeUInt = (
  scope: CheckFunction,
  funcName: string,
  argName: string
): CheckFunc => (p: DPoint): CheckFunction => {
  if (!p.clone().round()
    .equal(p) || !p.gtOrEqual(DPoint.zero())) {
    warn(`"${funcName}" -> "${argName}" should be UInt!`);
  }
  return scope;
};
 
const shouldBeDegree = (
  scope: CheckFunction,
  funcName: string,
  argName: string
): CheckFunc => (p: DPoint): CheckFunction => {
  if (!p.likeWorldGeodeticSystem) {
    warn(`"${funcName}" -> "${argName}" should be degree!`);
  }
  return scope;
};
 
const shouldBeRadians = (
  scope: CheckFunction,
  funcName: string,
  argName: string
): CheckFunc => (p: DPoint): CheckFunction => {
  if (!p.likeRadians) {
    warn(`"${funcName}" -> "${argName}" should be radians!`);
  }
  return scope;
};
 
const shouldExist = (
  scope: CheckFunction,
  funcName: string,
  argName: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): CheckFunc => (p: any): CheckFunction => {
  if (!isDefAndNotNull(p)) {
    warn(`"${funcName}" -> "${argName}" should exist!`);
  }
  return scope;
};
 
const shouldBeMeters = (
  scope: CheckFunction,
  funcName: string,
  argName: string
): CheckFunc => (p: DPoint): CheckFunction => {
  if (!p.likePseudoMercator) {
    warn(`"${funcName}" -> "${argName}" should be meters!`);
  }
  return scope;
};
 
export const checkFunction = (funcName: string): CheckFunction => ({
  // eslint-disable-next-line func-names, object-shorthand
  checkArgument: function(argName: string) {
    if (!DGeo.DEBUG) {
      return {
        shouldBeDegree: hook(this),
        shouldBeMeters: hook(this),
        shouldBeInt: hook(this),
        shouldBeUInt: hook(this),
        shouldBeRadians: hook(this),
        shouldExist: hook(this)
      };
    }
    return {
      shouldBeDegree: shouldBeDegree(this, funcName, argName),
      shouldBeMeters: shouldBeMeters(this, funcName, argName),
      shouldBeInt: shouldBeInt(this, funcName, argName),
      shouldBeUInt: shouldBeUInt(this, funcName, argName),
      shouldBeRadians: shouldBeRadians(this, funcName, argName),
      shouldExist: shouldExist(this, funcName, argName)
    };
  }
});
 
type ArrayFillFunction<T> = (index: number) => T;
 
/**
 * @param v
 * @param [fillSymbol=0]
 */
export const createArray = <T = number>(v: number, fillSymbol?: T | ArrayFillFunction<T>): T[] => {
  if (typeof fillSymbol === 'function') {
    return new Array(v).fill(false)
      .map((_, i) => (fillSymbol as ArrayFillFunction<T>)(i));
  }
  return new Array(v).fill(fillSymbol ?? 0);
};
 
type MatrixFillFunction<T> = (x: number, y: number) => T;
 
/**
 * @param h
 * @param w
 * @param [fillSymbol=0]
 */
export const createMatrix = <T>({h, w}: DPoint, fillSymbol?: T | MatrixFillFunction<T>): T[][] => {
  if (typeof fillSymbol === 'function') {
    return createArray(h)
      .map((_, y) => createArray<T>(w, (x) => (fillSymbol as MatrixFillFunction<T>)(x, y)));
  }
  return createArray(h)
    .map(() => createArray<T>(w, fillSymbol));
};
 
/**
 * [Gaussian elimination](https://en.wikipedia.org/wiki/Gaussian_elimination)
 * @param matrix
 */
export const gaussianElimination: {
  (matrix: number[][]): number[],
 
  /**
   * Min value if matrix contain 0.
   * @default 1e-10
   */
  MIN: number;
} = (matrix: number[][]): number[] => {
  const n = matrix.length;
  const matrixClone = createMatrix<number>(new DPoint(n + 1, n));
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n + 1; j++) {
      matrix[i][j] = matrix[i][j] === 0 ? gaussianElimination.MIN : matrix[i][j];
      matrixClone[i][j] = matrix[i][j];
    }
  }
 
  for (let k = 0; k < n; k++) {
    for (let i = 0; i < n + 1; i++) {
      matrixClone[k][i] /= matrix[k][k];
    }
    for (let i = k + 1; i < n; i++) {
      const K = matrixClone[i][k] / matrixClone[k][k];
      for (let j = 0; j < n + 1; j++) {
        matrixClone[i][j] -= matrixClone[k][j] * K;
      }
    }
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < n + 1; j++) {
        matrix[i][j] = matrixClone[i][j];
      }
    }
  }
 
  for (let k = n - 1; k > -1; k--) {
    for (let i = n; i > -1; i--) {
      matrixClone[k][i] /= matrix[k][k];
    }
    for (let i = k - 1; i > -1; i--) {
      const K = matrixClone[i][k] / matrixClone[k][k];
      for (let j = n; j > -1; j--) {
        matrixClone[i][j] -= matrixClone[k][j] * K;
      }
    }
  }
 
  const answer = createArray(n);
  for (let i = 0; i < n; i++) {
    answer[i] = matrixClone[i][n];
  }
 
  return answer;
};
gaussianElimination.MIN = 1e-10;
 
export type True = true;
 
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
export const createCanvas: {
 
  /**
   * Create dom canvas element with same width and height
   * @param size
   */
  (size: number): [HTMLCanvasElement, CanvasRenderingContext2D];
 
  /**
   * Create offscreen canvas with same width and height
   * @param size
   * @param offscreen
   */
  (size: number, offscreen: True): [OffscreenCanvas, OffscreenCanvasRenderingContext2D];
 
  /**
   * Create canvas by width and height
   * @param w
   * @param h
   */
  (w: number, h: number): [HTMLCanvasElement, CanvasRenderingContext2D];
 
  /**
   * Create offscreen canvas by width and height
   * @param w
   * @param h
   * @param offscreen
   */
  (w: number, h: number, offscreen: True): [OffscreenCanvas, OffscreenCanvasRenderingContext2D];
 
  /**
   * Create dom canvas element by `DPoint` size
   * @param size
   */
  (size: DPoint): [HTMLCanvasElement, CanvasRenderingContext2D];
 
  /**
   * Create offscreen canvas by `DPoint` size
   * @param size
   * @param offscreen
   */
  (size: DPoint, offscreen: True): [OffscreenCanvas, OffscreenCanvasRenderingContext2D];
 
  /**
   * Mock document object for tests
   */
  document?: Document;
} = (
  a: DPoint | number,
  b?: number | boolean,
  c?: boolean
): [HTMLCanvasElement | OffscreenCanvas, CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D] => {
  let w = 0;
  let h = 0;
  let offscreen = false;
  if (a instanceof DPoint) {
    const {x, y} = a;
    w = x;
    h = y;
  } else {
    w = a;
    h = a;
  }
  if (typeof b === 'boolean') {
    offscreen = b;
  } else Iif (typeof b === 'number') {
    h = b;
  }
  Iif (typeof c === 'boolean') {
    offscreen = c;
  }
  const canvas: HTMLCanvasElement | OffscreenCanvas =
    offscreen ? new OffscreenCanvas(w, h) : (createCanvas.document ?? document).createElement('canvas');
  Iif (!offscreen) {
    canvas.width = w;
    canvas.height = h;
  }
  return [canvas, canvas.getContext('2d')!];
};
 
/** @ignore */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const f = (a: any, b: any) => [].concat(...a.map((c: any) => b.map((d: any) => [].concat(c, d))));
 
/**
 * [Cartesian product](https://en.wikipedia.org/wiki/Cartesian_product)
 */
export const cartesianProduct: {
 
  /**
   * @param a
   * @param b
   */
  <T>(a: T[], ...b: T[][]): T[][];
 
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/explicit-module-boundary-types
} = <T>(a: T[], b: T[], ...c: T[][]): T[][] => b ? cartesianProduct(f(a, b), ...c) : a;
 
/**
 * Get all available combinations
 * @param arr
 */
export const getCombinations = <T>(arr: T[][]): T[][] => {
  if (arr.length === 1) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    return arr[0];
  }
  const ans: T[][] = [];
  const otherCases = getCombinations(arr.slice(1));
  for (let i = 0; i < otherCases.length; i++) {
    for (let j = 0; j < arr[0].length; j++) {
      ans.push([arr[0][j], ...otherCases[i]]);
    }
  }
  return ans;
};
 
export const div = (a: number, b: number): number => Math.floor(a / b);
 
export const toDegreesMinutesSeconds = (v: number): string => {
  const m = v < 0;
  const degrees = Math.floor(Math.abs(v));
  const t = (Math.abs(v) % 1) * 60;
  const minutes = Math.floor(t);
  const t2 = (t % 1) * 60;
  const seconds = t2.toFixed(2);
  return `${m ? '-' : ''}${degrees}° ${minutes}' ${seconds}"`;
};
 
export const parseDegreesMinutesSeconds = (i: string): number => {
  const parts = i.matchAll(/(?<value>-?\d+(?<tail>\.\d{1,})?)(?<type>°|'|")/gmiu);
  let d = 0;
  let m = 0;
  let s = 0;
 
  for (const part of parts) {
    switch (part?.groups?.type) {
      case '°':
        d = Number(part?.groups?.value ?? '0');
        break;
      case '\'':
        m = Number(part?.groups?.value ?? '0');
        break;
      case '"':
        s = Number(part?.groups?.value ?? '0');
        break;
      default:
    }
  }
 
  const h = d < 0 ? -1 : 1;
  return d + h * m / 60 + h * s / 3600;
};