Class UtilsSingleton

A utilities class providing mathematical, color, and geometric utility functions.

This class contains static-like methods for common utility operations including:

  • Mathematical operations (random numbers, interpolation, normalization)
  • Color manipulation and conversion
  • Geometric calculations (angles, distances, rotations)
  • Array and object utilities
  • Animation and transition helpers

UtilsSingleton

License

Utils is free software, available under the terms of a MIT style License.

Author

https://github.com/doubleactii

Example

import { Utils } from './utils';

// Generate a random number between 1 and 10
const randomNum = Utils.rand(1, 10);

// Convert RGB to hex
const hexColor = Utils.rgbToHex(255, 0, 0); // Returns "#ff0000"

// Calculate distance between two points
const distance = Utils.getDistance({x: 0, y: 0}, {x: 3, y: 4}); // Returns 5

Constructors

Properties

transitions: Record<string, any> = {}

Object storing all color objects being transitioned at the moment

storedIDs: string[] = []

An array storing all the reserved unique IDS

version: string = "VERSION_REPLACE_ME"

The version of the module.

logger: Logger

The logger module this module uses to log errors / logs

Methods

  • Generates a random decimal number between two numbers with a specified number of decimal places.

    Parameters

    • pNum1: number

      The first number to use for generating the random decimal number.

    • pNum2: number

      The second number to use for generating the random decimal number.

    • pPlaces: number = 1

      The number of decimal places to include in the generated random decimal number. Defaults to 1 if not provided.

    Returns number

    A random decimal number between the two numbers with the specified number of decimal places.

  • Generates a random decimal number between two numbers with a specified number of decimal places.

    Parameters

    • pNum1: number

      The first number to use for generating the random decimal number.

    • pNum2: number

      The second number to use for generating the random decimal number.

    Returns number

    A random decimal number between the two numbers with the specified number of decimal places.

  • Calculates the percentage of a value relative to a total value.

    Parameters

    • pValue: number

      The value to calculate the percentage of.

    • pTotalValue: number

      The total value to calculate the percentage relative to.

    Returns number

    The percentage of the value relative to the total value.

  • Clamps a number between a minimum and maximum value.

    Parameters

    • pNumber: number

      The number to clamp.

    • pMin: number = 0

      The minimum value to clamp the number to. Defaults to 0 if not provided.

    • pMax: number = 1

      The maximum value to clamp the number to. Defaults to 1 if not provided.

    Returns number

    The clamped number between the minimum and maximum values.

  • Linearly interpolates between two values by a specified amount.

    Parameters

    • pStart: number

      The start value to interpolate from.

    • pEnd: number

      The end value to interpolate to.

    • pAmount: number

      The amount to interpolate between the start and end values.

    Returns number

    The interpolated value between the start and end values based on the specified amount.

  • Linearly interpolates between two values by a specified amount and returns the result as a floored integer.

    Parameters

    • pStart: number

      The start value to interpolate from.

    • pEnd: number

      The end value to interpolate to.

    • pAmount: number

      The amount to interpolate between the start and end values.

    Returns number

    The interpolated value between the start and end values based on the specified amount, rounded down to the nearest integer.

  • Rounds a number to a specified number of decimal places.

    Parameters

    • pNumber: number

      The number to round.

    • pPlace: number = 1

      The number of decimal places to round to. Defaults to 1 if not provided.

    Returns number

    The rounded number to the specified number of decimal places.

  • Normalizes a value between a minimum and maximum value.

    Parameters

    • pVal: number

      The value to normalize.

    • pMin: number

      The minimum value for normalization.

    • pMax: number

      The maximum value for normalization.

    Returns number

    The normalized value between 0 and 1 based on the input value's position between the minimum and maximum values. If the difference between pMax and pMin is 0, returns 1 to avoid dividing by zero.

  • Normalizes a value between a minimum and maximum value, clamped to the range of -1 to 1.

    Parameters

    • pVal: number

      The value to normalize.

    • pMin: number

      The minimum value for normalization.

    • pMax: number

      The maximum value for normalization.

    Returns number

    The normalized and clamped value between -1 and 1 based on the input value's position between the minimum and maximum values. If the difference between pMax and pMin is 0, returns 1 to avoid dividing by zero.

  • Checks if a value is within a range of minimum and maximum values (inclusive).

    Parameters

    • pVal: number

      The value to check.

    • pMin: number

      The minimum value of the range to check against.

    • pMax: number

      The maximum value of the range to check against.

    Returns boolean

    True if the value is within the range (inclusive), false otherwise.

  • Formats a number by rounding it to the nearest integer and adding commas to separate thousands places.

    Parameters

    • pNum: number

      The number to format.

    Returns string

    A string representation of the formatted number.

  • Converts degrees to radians.

    Parameters

    • pDegrees: number

      The angle in degrees.

    Returns number

    The angle in radians.

  • Converts radians to degrees.

    Parameters

    • pRadians: number

      The angle in radians.

    Returns number

    The angle in degrees.

  • Returns a random element from the given array.

    Type Parameters

    • T

    Parameters

    • pArray: T[]

      The input array.

    Returns T

    A random element from the array.

  • Removes properties from an object except those listed in the exclude array.

    Parameters

    • pObject: Record<string, any>

      The object to remove properties from.

    • pExclude: string[]

      The array of property names to exclude from removal.

    Returns void

  • Returns true with probability proportional to the given number. The higher the number, the higher the chance of returning true.

    Parameters

    • pChance: number

      The probability value, between 0 and 100 (inclusive).

    Returns boolean

    Returns true or false, based on the probability value.

  • Gets the inverse direction of the direction passed

    Parameters

    • pDirection: string

      The direction to get the inverse of.

    Returns string

    The inverse direction

  • Calculates the angle (in radians) from a given direction.

    Parameters

    • pDirection: string

      The direction to calculate the angle from.

    Returns number

    The angle (in radians) associated with the given direction.

    Throws

    Throws an error if the direction is not recognized.

  • Centers a rectangle (defined by its dimensions) within a parent rectangle.

    Parameters

    • pChildWidth: number

      The width of the child rectangle.

    • pChildHeight: number

      The height of the child rectangle.

    • pParentWidth: number

      The width of the parent rectangle.

    • pParentHeight: number

      The height of the parent rectangle.

    • pParentX: number

      The x-coordinate of the parent rectangle.

    • pParentY: number

      The y-coordinate of the parent rectangle.

    Returns {
        x: number;
        y: number;
    }

    An object representing the new coordinates of the centered rectangle: { x: centerX, y: centerY }.

    • x: number
    • y: number

    Example

    const childWidth = 50;
    const childHeight = 30;
    const parentWidth = 100;
    const parentHeight = 80;
    const parentX = 20;
    const parentY = 10;
    const centeredCoordinates = centerRectangleOnParent(childWidth, childHeight, parentWidth, parentHeight, parentX, parentY);
    // Returns {x: 45, y: 35}
  • Generates a random angle in radians.

    Returns number

    A random angle in radians.

  • Gets the angle between two points

    Parameters

    • pStartPoint: {
          x: number;
          y: number;
      }

      The starting point

      • x: number
      • y: number
    • pEndPoint: {
          x: number;
          y: number;
      }

      The ending point

      • x: number
      • y: number

    Returns number

    The angle between the starting point and the ending point

  • Gets the angle between two points but in VYLO / PIXI coordinate space. Removes 180 degrees from a raw angle

    Parameters

    • pStartPoint: {
          x: number;
          y: number;
      }

      The starting point

      • x: number
      • y: number
    • pEndPoint: {
          x: number;
          y: number;
      }

      The ending point

      • x: number
      • y: number

    Returns number

    The angle between the starting point and the ending point

  • Converts a raw angle to be the proper angle in Vylocity. By removing 180 degrees

    Parameters

    • pAngle: number

      The angle to convert.

    Returns number

    The converted angle

  • Gets the minimal value between the value to add and the maximum allowed value.

    Parameters

    • pCurrent: number

      The current value.

    • pAdd: number

      The value to add to the current value.

    • pMax: number

      The maximum value that can be reached.

    Returns number

    The minimal value between the value to add and the remaining value to reach the maximum.

  • Calculates the Euclidean distance between two points in a two-dimensional space.

    Parameters

    • pStartPoint: {
          x: number;
          y: number;
      }

      The starting point with x and y coordinates.

      • x: number

        The x-coordinate of the starting point.

      • y: number

        The y-coordinate of the starting point.

    • pEndPoint: {
          x: number;
          y: number;
      }

      The ending point with x and y coordinates.

      • x: number

        The x-coordinate of the ending point.

      • y: number

        The y-coordinate of the ending point.

    Returns number

    The Euclidean distance between the two points.

    Example

    const startPoint = { x: 1, y: 2 };
    const endPoint = { x: 4, y: 6 };
    const distance = getDistance(startPoint, endPoint); // 5
    // Returns the Euclidean distance between the points (1, 2) and (4, 6).
  • Calculates the new position of a point based on distance and angle.

    Parameters

    • pPoint: {
          x: number;
          y: number;
      }

      The initial position of the point with x and y coordinates.

      • x: number

        The initial x-coordinate of the point.

      • y: number

        The initial y-coordinate of the point.

    • pDistance: number

      The distance by which to move the point.

    • pAngle: number

      The angle (in radians) at which to move the point.

    Returns {
        x: number;
        y: number;
    }

    The new position of the point after moving by the specified distance and angle.

    • x: number
    • y: number

    Example

    const initialPosition = { x: 10, y: 20 };
    const distance = 5;
    const angleInRadians = 0.785398; // 45 degrees
    const newPosition = calculateNewPositionFromDistanceAndAngle(initialPosition, distance, angleInDegrees);
    // Returns the new position of the point after moving by 5 units at a 45-degree angle.
  • Calculates the proportional length based on a current value, a maximum value, and a specified total length.

    Parameters

    • pCurrent: number

      The current value to be scaled.

    • pMax: number

      The maximum value for scaling.

    • pTotalLength: number

      The specified total length.

    Returns number

    The proportional length based on the current value, maximum value, and total length.

    Example

    const current = 25;
    const max = 50;
    const totalLength = 100;
    const proportionalLength = calculateProportionalLength(current, max, totalLength); // 50
    // Returns the proportional length based on the current value, maximum value, and total length.
  • Calculates the compass direction based on the given angle.

    Parameters

    • pAngle: number

      The angle in radians.

    Returns string

    The compass direction (e.g., 'east', 'southeast', 'south', etc.).

    Example

    const angle = Math.PI / 4; // 45 degrees in radians
    const direction = getDirection(angle); // Returns 'northeast'
  • Calculates the linear decay of a variable over time.

    Parameters

    • pInitialValue: number

      The initial value of the variable.

    • pCurrentTime: number

      The current time at which to calculate the variable value.

    • pMaxTime: number

      The maximum time for the decay process.

    • pDecayRate: number = 0.5

      The decay rate (default is 0.5).

    Returns number

    The remaining value of the variable after linear decay.

    Example

    const initialValue = 100;
    const currentTime = 50;
    const maxTime = 1000;
    const decayRate = 0.3;
    const remainingValue = linearDecay(initialValue, currentTime, maxTime, decayRate);
    // Returns the remaining value after linear decay.
  • Generates a unique id

    Parameters

    • pIDLength: number = 7

      The length of the ID to create

    Returns string

    A unique ID

  • Converts a color in decimal format into hex format

    Parameters

    • pDecimal: number

      The color in decimal format

    • pChars: number = 6

      The length to make the hex string

    Returns string

    The decimal color converted into hex format

  • Add intensity to this color to get a brighter or dimmer effect

    Parameters

    • pColor: string | number

      Color in hex format or decimal format

    • pPercent: number

      The percent of brightness to add to this color

    Returns string

  • Converts an RGB color value to a hexadecimal color value.

    Parameters

    • pR: number

      The red component of the RGB color value (0-255).

    • pG: number

      The green component of the RGB color value (0-255).

    • pB: number

      The blue component of the RGB color value (0-255).

    Returns string

  • Converts a hexadecimal color value to an RGB color value.

    Parameters

    • pHex: string

      The hexadecimal color value to convert (e.g. "#FF0000" for red).

    Returns number[]

    An array containing the red, green, and blue components of the RGB color value.

  • Converts RGB color values to a decimal value.

    Parameters

    • pR: number

      The red component of the RGB color value (0-255).

    • pG: number

      The green component of the RGB color value (0-255).

    • pB: number

      The blue component of the RGB color value (0-255).

    Returns number

  • Converts a hexadecimal color value to a decimal value.

    Parameters

    • pHex: string

      The hexadecimal color value to convert (e.g. "#FF0000" for red).

    Returns number

    The decimal representation of the hexadecimal color value.

  • Convert a color to different formats or get a random color

    Parameters

    • pSwitch: string | number = ...

      A hex string representing a color (with or without the tag) A color formatted in the decimal format. Or the r value of a rgb color.

    • Optional pG: number

      g value of a rgb color

    • Optional pB: number

      b value of a rgb color

    Returns {
        hex: string;
        hexTagless: string;
        rgb: string;
        rgbArray: number[];
        rgbObject: {
            r: number;
            g: number;
            b: number;
        };
        rgbNormal: number[];
        decimal: number;
    }

    A color object with various different export options. hex, hexTagless, rgb, rgbArray, rgbObject, rgbNormal, decimal formats.

    • hex: string
    • hexTagless: string
    • rgb: string
    • rgbArray: number[]
    • rgbObject: {
          r: number;
          g: number;
          b: number;
      }
      • r: number
      • g: number
      • b: number
    • rgbNormal: number[]
    • decimal: number
  • Gets a random color

    Returns string

    A random color in the hex format

  • Gets a random color between two colors

    Parameters

    • pColor1: string | number

      The first color to get a color between

    • pColor2: string | number

      The second color to get a color between

    • pAmount: number = 0.5

      The closer the random color will be to either input colors on a range of 0-1 0 to 0.5 (closer to pColor1) 0.5 to 1 (closer to pColor2)

    Returns number

    A random color in the decimal format

  • Transition a color to another color in pDuration time.

    Parameters

    • pInstance: any

      The instance to transition it's color property. pInstance's color will be transitioned either via pInstance.color = newColor or pInstance.color.tint = newColor (if the color is defined as an object)

    • pStartColor: string | number = '#000'

      The start color

    • pEndColor: string | number = '#fff'

      The end color

    • pDuration: number = 1000

      The duration of the transition

    • Optional pIterativeCallback: ((color) => void)

      Callback to call every tick of the transition

        • (color): void
        • Parameters

          • color: any

          Returns void

    • Optional pEndCallback: ((color) => void)

      Callback to call at the end of the transition

        • (color): void
        • Parameters

          • color: any

          Returns void

    Returns string

    An ID that references this transition to be passed to cancelTransition to stop an ongoing transition.

  • Cancels an ongoing transition

    Parameters

    • pID: string

      The ID of the ongoing transition to cancel

    Returns void

  • Calculates the position of a point after rotating it around a center point by a given angle.

    Parameters

    • pRect: {
          x: number;
          y: number;
          width: number;
          height: number;
          anchor?: {
              x?: number;
              y?: number;
          };
      }

      The rectangle object to rotate the point around. pRect.anchor.x and pRecent.anchor.y is used to control the "center" of the rectangle.

      • x: number
      • y: number
      • width: number
      • height: number
      • Optional anchor?: {
            x?: number;
            y?: number;
        }
        • Optional x?: number
        • Optional y?: number
    • pTheta: number

      The angle (in radians) to rotate the point by.

    • pPoint: {
          x: number;
          y: number;
      }

      The point object to rotate around the center of the rectangle.

      • x: number

        The x-coordinate of the point to rotate.

      • y: number

        The y-coordinate of the point to rotate.

    Returns {
        x: number;
        y: number;
    }

    An object with the rotated point's new x and y coordinates.

    • x: number
    • y: number
  • Calculates the position of a rectangle's corner points and center point after rotating it around a center point by a given angle.

    Parameters

    • pRect: {
          x: number;
          y: number;
          width: number;
          height: number;
          anchor?: {
              x?: number;
              y?: number;
          };
      }

      The rectangle object to rotate the point around. pRect.anchor.x and pRecent.anchor.y is used to control the "center" of the rectangle.

      • x: number
      • y: number
      • width: number
      • height: number
      • Optional anchor?: {
            x?: number;
            y?: number;
        }
        • Optional x?: number
        • Optional y?: number
    • pTheta: number

      The angle (in radians) to rotate the point by.

    Returns {
        tl: {
            x: number;
            y: number;
        };
        tr: {
            x: number;
            y: number;
        };
        bl: {
            x: number;
            y: number;
        };
        br: {
            x: number;
            y: number;
        };
        center: {
            x: number;
            y: number;
        };
    }

    An object with the rotated rectangle's new corner points and center points.

    • tl: {
          x: number;
          y: number;
      }
      • x: number
      • y: number
    • tr: {
          x: number;
          y: number;
      }
      • x: number
      • y: number
    • bl: {
          x: number;
          y: number;
      }
      • x: number
      • y: number
    • br: {
          x: number;
          y: number;
      }
      • x: number
      • y: number
    • center: {
          x: number;
          y: number;
      }
      • x: number
      • y: number
  • Calculate the icon offset to compensate for a non-zero anchor.

    Parameters

    • pIconSize: {
          width: number;
          height: number;
      } = ...

      The size of the icon with properties .x and .y.

      • width: number

        The size of the icon's width.

      • height: number

        The size of the icon's height'.

    • pAnchor: {
          x: number;
          y: number;
      } = ...

      The anchor point with properties .x and .y.

      • x: number

        The anchor's x value.

      • y: number

        The anchor's y value.

    • pScale: {
          x: number;
          y: number;
      } = ...

      The scale factor applied to the object with properties .x and .y.

      • x: number

        The scale's y value.

      • y: number

        The scale's y value.

    Returns {
        x: number;
        y: number;
    }

    The calculated icon offset with properties .x and .y.

    • x: number
    • y: number