All files / utils math.ts

98.24% Statements 168/171
91.08% Branches 92/101
94.87% Functions 37/39
97.77% Lines 132/135

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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638        94x 94x                 94x 1465x 1465x               94x 8102x               94x                   94x       5295x         5295x                 94x       330x 330x     330x                 94x       2723x 2723x                 94x       266x 266x                                   94x         1728x 1728x 1728x 1728x     1728x 5x 1723x 103x 1620x 13x   1607x     1728x                                                                                                                                                               94x         74x 74x 74x   74x 6x 68x 66x 66x 66x 66x 66x     74x 74x 48x     43x 43x 25x   18x     48x     74x                   94x 4673x                 94x 10x                 94x 574x 461x                   94x 3x 14x                   94x 72x                   94x 3328x               94x   4932x 1863x       4932x                   94x                   1566x             94x                               94x 1559x 1559x 1559x   1559x                                     94x       163x             94x 26x                   94x 5x 5x                             94x 5x                                                                                                         94x     572x 572x         572x 572x   572x 572x   572x 572x 572x   28x 28x 28x 544x 544x 544x 544x   544x 544x 544x     572x                                   94x             2x 2x   2x 18x               18x     2x 18x 18x                 18x 2x                   94x       351x 6x     1063x                   94x     158x                   94x     2x                           94x 525x      
/**
 * @module Utils
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import { Point, Vector, AtLeastOne } from "@lisn/globals/types";
 
/**
 * Round a number to the given decimal precision.
 *
 * @category Math
 */
export const roundNumTo = (value: number, numDecimal = 0) => {
  const multiplicationFactor = MH.pow(10, numDecimal);
  return MH.round(value * multiplicationFactor) / multiplicationFactor;
};
 
/**
 * Returns true if the given value is a valid _finite_ number.
 *
 * @category Validation
 */
export const isValidNum = (value: unknown): value is number =>
  MH.isNumber(value) && MC.NUMBER.isFinite(value);
 
/**
 * Returns true if the given value is a valid _finite_ number or a numerical
 * string.
 *
 * @category Validation
 */
export const isValidNumerical = (
  value: unknown,
): value is number | `${number}` => !!toNum(value, false);
 
/**
 * If the given value is a valid _finite_ number, it is returned, otherwise
 * the default is returned.
 *
 * @category Math
 */
export const toNum = <D extends number | false | null = 0>(
  value: unknown,
  defaultValue: D | 0 = 0,
): number | D => {
  const numValue = MH.isLiteralString(value) ? MH.parseFloat(value) : value;
 
  // parseFloat will strip trailing non-numeric characters, so we check that
  // the parsed number is equal to the string, if it was a string, using loose
  // equality, in order to make sure the entire string was a number.
  return isValidNum(numValue) && numValue == value ? numValue : defaultValue;
};
 
/**
 * If the given value is a valid _finite integer_ number, it is returned,
 * otherwise the default is returned.
 *
 * @category Math
 */
export const toInt = <D extends number | false | null = 0>(
  value: unknown,
  defaultValue: D | 0 = 0,
): number | D => {
  let numValue = toNum(value, null);
  numValue = numValue === null ? numValue : MH.floor(numValue);
 
  // Ensure that the parsed int equaled the original by loose equality.
  return isValidNum(numValue) && numValue == value ? numValue : defaultValue;
};
 
/**
 * If the given value is a valid non-negative _finite_ number, it is returned,
 * otherwise the default is returned.
 *
 * @category Math
 */
export const toNonNegNum = <D extends number | false | null = 0>(
  value: unknown,
  defaultValue: D | 0 = 0,
): number | D => {
  const numValue = toNum(value, null);
  return numValue !== null && numValue >= 0 ? numValue : defaultValue;
};
 
/**
 * If the given value is a valid positive number, it is returned, otherwise the
 * default is returned.
 *
 * @category Math
 */
export const toPosNum = <D extends number | false | null = 0>(
  value: unknown,
  defaultValue: D | 0 = 0,
): number | D => {
  const numValue = toNum(value, null);
  return numValue !== null && numValue > 0 ? numValue : defaultValue;
};
 
/**
 * Returns the given number bound by min and/or max value.
 *
 * If the value is not a valid number, then `defaultValue` is returned if given
 * (_including if it is null_), otherwise `limits.min` if given and not null,
 * otherwise `limits.max` if given and not null, or finally 0.
 *
 * If the value is outside the bounds, then:
 * - if `defaultValue` is given, `defaultValue` is returned (_including if it
 *   is null_)
 * - otherwise, the min or the max value (whichever one is violated) is
 *   returned
 *
 * @category Math
 */
export const toNumWithBounds = <D extends number | false | null = number>(
  value: unknown,
  limits: AtLeastOne<{ min: number | null; max: number | null }>,
  defaultValue?: D,
): number | D => {
  const isDefaultGiven = defaultValue !== undefined;
  const numValue = toNum(value, null);
  const min = limits?.min ?? null;
  const max = limits?.max ?? null;
 
  let result: number | D;
  if (!isValidNum(numValue)) {
    result = isDefaultGiven ? defaultValue : (min ?? max ?? 0);
  } else if (min !== null && numValue < min) {
    result = isDefaultGiven ? defaultValue : min;
  } else if (max !== null && numValue > max) {
    result = isDefaultGiven ? defaultValue : max;
  } else {
    result = numValue;
  }
 
  return result;
};
 
/**
 * Used as a custom calculator for {@link toRawNum}. The function should return
 * the final numerical result.
 *
 * @since v1.3.0
 *
 * @category Math
 */
export type RawNumberCalculator = (props: {
  /**
   * The original value passed to {@link toRawNum}
   */
  input: unknown;
 
  /**
   * Whether `+` or `-` prefix is present in {@link input}. At least one of
   * {@link isAdditive} or {@link isPercent} is guaranteed to be true.
   */
  isAdditive: boolean;
 
  /**
   * Whether `%` suffix is present in {@link input}. At least one of
   * {@link isAdditive} or {@link isPercent} is guaranteed to be true.
   */
  isPercent: boolean;
 
  /**
   * The actual numerical value of {@link input} after stripping the `%` suffix
   * if any, but not the prefix (i.e. it will be negative if there was a `-`
   * prefix)
   */
  numerical: number;
}) => number;
 
/**
 * Converts the given {@link RawOrRelativeNumber} to a raw number using the
 * given reference or calculator function. If the final result is invalid, the
 * default is returned.
 *
 * The default calculation process, if `input` is relative and if
 * `referenceOrCalculator` is only a number is as follows:
 * - If `input` is percentage, it is multiplied with the reference value.
 *   Afterwards, if `input` also has a `+` or `-` prefix, the resulting
 *   percentage is added to the reference. I.e:
 *   - `"30%"` results in `0.3 * reference`
 *   - `"+30%"` results in `1.3 * reference`
 *   - `"-30%"` results in `0.7 * reference`
 * - Otherwise, if `input` only has a `+` or `-` prefix it is added or
 *   subtracted from the reference.
 *
 * @param input     If it's a pure number or a positive numerical string without
 *                  `+` prefix, it is treated as the raw value to use and no
 *                  reference or further calculation is used. Otherwise the raw
 *                  value is calculated using `referenceOrCalculator`
 * @param referenceOrCalculator
 *                  If given as a number, it will be the reference value used
 *                  with the default calculation process (see above).
 *                  Otherwise, if given as a function, then it is used as the
 *                  calculator and its return value is used as the final result.
 *
 * @since v1.3.0
 *
 * @example
 * If you want to use the default calculator function, but specify a custom
 * reference value based on the type of input, you could call {@link toRawNum}
 * recursively like so:
 *
 * ```javascript
 * const calculator = ({input, isAdditive, isPercent, numerical}) => {
 *   return toRawNum(input, isAdditive && isPercent ? referenceA : referenceB);
 * }
 *
 * toRawNum(input, calculator);
 * ```
 *
 * @category Math
 */
export const toRawNum = <D extends number | false | null = 0>(
  input: unknown,
  referenceOrCalculator: number | RawNumberCalculator,
  defaultValue?: D,
) => {
  let numerical = NaN,
    isAdditive = false,
    isPercent = false;
 
  if (MH.isNumber(input)) {
    numerical = input;
  } else if (MH.isString(input)) {
    const opA = input.slice(0, 1);
    const opB = input.slice(-1);
    isAdditive = opA === "+" || opA === "-";
    isPercent = opB === "%";
    numerical = toNum(isPercent ? input.slice(0, -1) : input, NaN);
  }
 
  let result = numerical;
  if (isAdditive || isPercent) {
    const calculator: RawNumberCalculator = MH.isFunction(referenceOrCalculator)
      ? referenceOrCalculator
      : ({ isAdditive, isPercent, numerical }) => {
          const reference = referenceOrCalculator;
          if (isPercent) {
            return (reference * numerical) / 100 + (isAdditive ? reference : 0);
          }
          return reference + numerical;
        };
 
    result = calculator({ input, isAdditive, isPercent, numerical });
  }
 
  return toNum(result, defaultValue);
};
 
/**
 * Returns the largest absolute value among the given ones.
 *
 * The result is always positive.
 *
 * @category Math
 */
export const maxAbs = (...values: number[]) =>
  MH.max(...values.map((v) => MH.abs(v)));
 
/**
 * Returns the smallest absolute value among the given ones.
 *
 * The result is always positive.
 *
 * @category Math
 */
export const minAbs = (...values: number[]) =>
  MH.min(...values.map((v) => MH.abs(v)));
 
/**
 * Returns the value with the largest absolute value among the given ones.
 *
 * The result can be negative.
 *
 * @category Math
 */
export const havingMaxAbs = (...values: number[]): number =>
  MH.lengthOf(values)
    ? values.sort((a, b) => MH.abs(b) - MH.abs(a))[0]
    : -MC.INFINITY;
 
/**
 * Returns the value with the smallest absolute value among the given ones.
 *
 * The result can be negative.
 *
 * @category Math
 */
export const havingMinAbs = (...values: number[]) =>
  MH.lengthOf(values)
    ? values.sort((a, b) => MH.abs(a) - MH.abs(b))[0]
    : MC.INFINITY;
 
/**
 * Returns the sum of the given values.
 *
 * @since v1.3.0
 *
 * @category Math
 */
export const sum = (...values: number[]) =>
  values.reduce((total, current) => total + current, 0);
 
/**
 * Returns the angle (in radians) that the vector defined by the given x, y
 * makes with the positive horizontal axis.
 *
 * The angle returned is in the range -PI to PI, not including -PI.
 *
 * @category Math
 */
export const hAngle = (x: number, y: number) =>
  normalizeAngle(MC.MATH.atan2(y, x)); // ensure that -PI is transformed to +PI
 
/**
 * Normalizes the given angle (in radians) so that it's in the range -PI to PI,
 * not including -PI.
 *
 * @category Math
 */
export const normalizeAngle = (a: number) => {
  // ensure it's positive in the range 0 to 2 PI
  while (a < 0 || a > MC.PI * 2) {
    a += (a < 0 ? 1 : -1) * MC.PI * 2;
  }
 
  // then, if > PI, offset by - 2PI
  return a > MC.PI ? a - MC.PI * 2 : a;
};
 
/**
 * Normalizes a vector defined by the given x, y and z coordinates to length 1.
 *
 * @since v1.3.0
 *
 * @category Math
 */
export const normalizeAxis = (x: number, y: number, z = 0) => {
  const len = MH.sqrt(x * x + y * y + z * z);
  return len > 0 ? [x / len, y / len, z / len] : [0, 0, 0];
};
 
/**
 * Converts the given angle in degrees to radians.
 *
 * @category Math
 */
export const degToRad = (a: number) => (a * MC.PI) / 180;
 
/**
 * Converts the given angle in radians to degrees.
 *
 * @category Math
 */
export const radToDeg = (a: number) => (a * 180) / MC.PI;
 
/**
 * Returns true if the given vectors point in the same direction.
 *
 * @param angleDiffThreshold
 *                  Sets the threshold in degrees when comparing the angles of
 *                  two vectors. E.g. for 5 degrees threshold, directions
 *                  whose vectors are within 5 degrees of each other are
 *                  considered parallel.
 *                  It doesn't make sense for this value to be < 0 or >= 90
 *                  degrees. If it is, it's forced to be positive (absolute)
 *                  and <= 89.99.
 *
 * @category Math
 */
export const areParallel = (vA: Vector, vB: Vector, angleDiffThreshold = 0) => {
  const angleA = hAngle(vA[0], vA[1]);
  const angleB = hAngle(vB[0], vB[1]);
  angleDiffThreshold = MH.min(89.99, MH.abs(angleDiffThreshold));
 
  return (
    MH.abs(normalizeAngle(angleA - angleB)) <= degToRad(angleDiffThreshold)
  );
};
 
/**
 * Returns true if the given vectors point in the opposite direction.
 *
 * @param angleDiffThreshold
 *                  Sets the threshold in degrees when comparing the angles of
 *                  two vectors. E.g. for 5 degrees threshold, directions
 *                  whose vectors are within 175-185 degrees of each other are
 *                  considered antiparallel.
 *                  It doesn't make sense for this value to be < 0 or >= 90
 *                  degrees. If it is, it's forced to be positive (absolute)
 *                  and <= 89.99.
 *
 * @category Math
 */
export const areAntiParallel = (
  vA: Vector,
  vB: Vector,
  angleDiffThreshold = 0,
) => areParallel(vA, [-vB[0], -vB[1]], angleDiffThreshold);
 
/**
 * Returns the distance between two points on the screen.
 *
 * @category Math
 */
export const distanceBetween = (ptA: Point, ptB: Point) =>
  MH.sqrt(MH.pow(ptA[0] - ptB[0], 2) + MH.pow(ptA[1] - ptB[1], 2));
 
/**
 * Returns the two roots of the quadratic equation with coefficients
 * `a`, `b` & `c`, i.e. `a * x^2 + b * x + c = 0`
 *
 * The roots may be `NaN` if the quadratic has no real solutions.
 *
 * @category Math
 */
export const quadraticRoots = (a: number, b: number, c: number) => {
  const z = MH.sqrt(b * b - 4 * a * c);
  return [(-b + z) / (2 * a), (-b - z) / (2 * a)];
};
 
/**
 * Returns the value that an "easing" quadratic function would have at the
 * given x.
 *
 * @see https://easings.net/#easeInOutQuad
 *
 * @param x Must be between 0 and 1.
 *
 * @returns The current y-axis value between 0 and 1.
 *
 * @category Math
 */
export const easeInOutQuad = (x: number) =>
  x < 0.5 ? 2 * x * x : 1 - MH.pow(-2 * x + 2, 2) / 2;
 
/**
 * @since v1.3.0
 *
 * @category Math
 */
export type CriticallyDampedSettings = {
  lTarget: number;
  dt: number;
  lag: number;
  l?: number;
  v?: number;
  precision?: number;
};
 
/**
 * @since v1.3.0
 *
 * @category Math
 */
export type CriticallyDampedState = {
  l: number;
  v: number;
  dlFr: number;
};
 
/**
 * Returns the new position and velocity for a critically damped user-driven
 * spring state toward a current target position.
 *
 * @param [settings.lTarget]       Target final position.
 * @param [settings.dt]            Time step in milliseconds since the last call.
 *                                 Must be small for the returned values to be
 *                                 meaningful.
 * @param [settings.lag]           Lag in milliseconds (how long it should take
 *                                 for it to reach the final position). Must be
 *                                 positive.
 * @param [settings.l = 0]         Current position (starting or one returned by
 *                                 previous call).
 * @param [settings.v = 0]         Current velocity (returned by previous call).
 * @param [settings.precision = 2] Number of decimal places to round position to
 *                                 in order to determine when it's "done".
 *
 * @returns Updated
 * - `l`: position
 * - `v`: velocity
 * - `dlFr`: fractional change in position since the last call
 *
 * @since v1.2.0 (Fractional change in position in return value was added in v1.3.0)
 *
 * @category Math
 */
export const criticallyDamped = (
  settings: CriticallyDampedSettings,
): CriticallyDampedState => {
  const { lTarget, precision = 2 } = settings;
  const lag = toNumWithBounds(settings.lag, { min: 1 }) / 1000; // to seconds
 
  // Since the position only approaches asymptotically the target it never truly
  // reaches it exactly we need an approximation to calculate w0. N determines
  // how far away from the target position we are after `lag` milliseconds.
  const N = 7;
  const w0 = N / lag;
 
  let { l = 0, v = 0, dt } = settings;
  dt /= 1000; // to seconds
 
  const lPrev = l;
  let dlFr = 0;
  if (roundNumTo(l - lTarget, precision) === 0) {
    // we're done
    l = lTarget;
    v = 0;
    dlFr = 1;
  } else if (dt > 0) {
    const A = l - lTarget;
    const B = v + w0 * A;
    const e = MH.exp(-w0 * dt);
 
    l = lTarget + (A + B * dt) * e;
    v = (B - w0 * (A + B * dt)) * e;
    dlFr = (l - lPrev) / (lTarget - lPrev);
  }
 
  return { l, v, dlFr };
};
 
/**
 * An iterator version of {@link criticallyDamped}.
 *
 * @returns An iterator whose `next` method accepts an optional object with
 * updated settings.
 * The iterator yields an object containing successive values for:
 * - `l`: position
 * - `v`: velocity
 * - `t`: total time elapsed
 * - `dlFr`: fractional (from 0 to 1) change in position since the last frame
 *
 * @since v1.3.0
 *
 * @category Math
 */
export function* newCriticallyDampedIterator(
  settings: CriticallyDampedSettings,
): Generator<
  CriticallyDampedState,
  CriticallyDampedState,
  Partial<CriticallyDampedSettings>
> {
  let { lTarget, dt, lag, l, v, precision } = settings;
  let dlFr = 0;
 
  const next = () => {
    ({ l, v, dlFr } = criticallyDamped({
      lTarget,
      lag,
      l,
      dt,
      v,
      precision,
    }));
    return { l, v, dlFr };
  };
 
  while (true) {
    const result = next();
    ({
      lTarget = lTarget,
      dt = dt,
      lag = lag,
      l = l,
      v = v,
      precision = precision,
    } = (yield result) ?? {});
 
    if (l === lTarget) {
      return result;
    }
  }
}
 
/**
 * Returns an array of object's keys sorted by the numeric value they hold.
 *
 * @category Math
 */
export const sortedKeysByVal = <T extends Record<string, number>>(
  obj: T,
  descending = false,
): Array<keyof T> => {
  if (descending) {
    return MH.keysOf(obj).sort((x: keyof T, y: keyof T) => obj[y] - obj[x]);
  }
 
  return MH.keysOf(obj).sort((x: keyof T, y: keyof T) => obj[x] - obj[y]);
};
 
/**
 * Returns the key in the given object which holds the largest numeric value.
 *
 * If the object is empty, returns `undefined`.
 *
 * @category Math
 */
export const keyWithMaxVal = (
  obj: Record<string, number>,
): string | undefined => {
  return MH.lastOf(sortedKeysByVal(obj));
};
 
/**
 * Returns the key in the given object which holds the smallest numeric value.
 *
 * If the object is empty, returns `undefined`.
 *
 * @category Math
 */
export const keyWithMinVal = (
  obj: Record<string, number>,
): string | undefined => {
  return MH.firstOf(sortedKeysByVal(obj));
};
 
/**
 * Takes two integers and returns a bitmask that covers all values between
 * 1 << start and 1 << end, _including the starting and ending one_.
 *
 * If pStart > pEnd, they are reversed.
 *
 * getBitmask(start, start) always returns 1 << start
 * getBitmask(start, end) always returns same as getBitmask(end, start)
 *
 * @category Math
 */
export const getBitmask = (start: number, end: number): number =>
  start > end
    ? getBitmask(end, start)
    : (~0 >>> (32 - end - 1 + start)) << start;