Equetronic Helpers

Description

The equetronic-helpers is a repo that is added as a submodule in the other repos. This repo contains and maintains all logic and functions regarding calculations of EHM data and front end logic regarding geo-locations, checkpoint crossing etc.

Methods

getMapMarkers(markers)

This method accepts an array of markers and returns an array of map markers. Each map marker has an ID, a name, and a position that consists of a latitude and a longitude.

Arguments:

  • markers (Array): An array of markers.

Return Type:

  • Array: An array of map markers. Each map marker has the following properties:
    • id (Number): The ID of the marker.
    • name (String): The name of the marker.
    • position (Object): An object containing the latitude and longitude of the marker's position.

Example Return:

[
    {
        id: 1,
        name: "Marker 1",
        position: {
            lat: 51.5074,
            lng: -0.1278
        }
    },
    {
        id: 2,
        name: "Marker 2",
        position: {
            lat: 52.5200,
            lng: 13.4050
        }
    },
    // ... more markers
]

dmsToDdLat(text)

This method accepts a string representing a latitude in DMS format (degrees, minutes, seconds), and returns the latitude in decimal degrees (DD).

Arguments:

  • text (String): A string representing a latitude in DMS format.

Return Type:

  • Number: The latitude in decimal degrees.

Example Usage:

let result = this.dmsToDdLat('45° 30\' 30" N'); // 45.50833333

dmsToDdLng(text)

This method accepts a string representing a longitude in DMS format (degrees, minutes, seconds), and returns the longitude in decimal degrees (DD).

Arguments:

  • text (String): A string representing a longitude in DMS format.

Return Type:

  • Number: The longitude in decimal degrees.

Example Usage:

let result = this.dmsToDdLng('73° 45\' 0" W'); // -73.75

removeElementsAfterLimit(arr, limit)

This method accepts an array and a limit, and returns a new array with the same elements as the original array up to the limit.

Arguments:

  • arr (Array): The array to be limited.
  • limit (Number): The maximum number of elements to be returned.

Return Type:

  • Array: A new array with the same elements as the original array up to the limit.

Example Usage:

let result = this.removeElementsAfterLimit([1,2,3,4,5], 3); // [1,2,3]

getMarkerPins(list, timezone)

This method accepts an array of marker pins and a timezone, and returns an array of pins. Each pin has an ID, an index, a time, a name, a tooltip, and a position that consists of a latitude and a longitude.

Arguments:

  • list (Array): An array of marker pins.
  • timezone (String): A timezone string.

Return Type:

  • Array: An array of pins. Each pin has the following properties:
    • id (Number): The ID of the pin.
    • index (Number): The index of the pin.
    • time (String): The time of the pin in the given timezone.
    • name (String): The name of the pin.
    • tooltip (String): A tooltip string.
    • position (Object): An object containing the latitude and longitude of the pin's position.

Example Return:

[
    {
        id: 1,
        index: 0,
        time: "08:00:00",
        name: "Pin 1",
        tooltip: "Time: 08:00:00 | Heart Rate: 120 | Speed: 10",
        position: {
            lat: 51.5074,
            lng: -0.1278
        }
    },
    {
        id: 2,
        index: 1,
        time: "08:05:00",
        name: "Pin 2",
        tooltip: "Time: 08:05:00 | Heart Rate: 110 | Speed: 12",
        position: {
            lat: 52.5200,
            lng: 13.4050
        }
    },
    // ... more pins
]

getMarkerPointers(markers, map_configs)

This method accepts an array of markers and a map configuration object, and returns an array of pointers. Each pointer has a checkpoint extension, a marker ID, a marker name, and a list of items that consist of an ID, a name, a marker ID, a map ID, a latitude, a longitude, and an x-y position.

Arguments:

  • markers (Array): An array of markers.
  • map_configs (Object): A map configuration object.

Return Type:

  • Array: An array of pointers. Each pointer has the following

addAdditionalDataFields(current_data, pointers, data_list, map_configs)

This method accepts four parameters: current_data, pointers, data_list, and map_configs. It adds additional data fields to the current_data object based on the input data and returns the updated current_data object.

Arguments:

  • current_data (Object): The current data object.
  • pointers (Array): An array of pointers.
  • data_list (Array): An array of data.
  • map_configs (Object): An object containing map configurations.

Return Type:

  • Object: The updated current_data object with additional data fields.

Example Return:

{
    ...current_data,
    xy_positions: {x: 234.567, y: 123.456},
    stride: 1.2,
    stride_between_data: 0.8,
    split_time: 3.2,
    avg_speed: 5.4,
    avg_stride: 0.9,
    avg_heart_rate: 75
}

getStrideBetweenData(data)

This method accepts an array of data and calculates the stride difference between the current and previous data.

Arguments:

  • data (Array): An array of data.

Return Type:

  • Number: The stride difference between the current and previous data.

Example Return:

0.85

getStride(data)

This method accepts an array of data and calculates the stride difference between the current and previous checkpoint.

Arguments:

  • data (Array): An array of data.

Return Type:

  • Number: The stride difference between the current and previous checkpoint.

Example Return:

1.23

getAverageValues(data, pointers)

This method accepts an array of data and an array of pointers and returns an object with the average speed, stride, and heart rate values.

Arguments:

  • data (Array): An array of data.
  • pointers (Array): An array of pointers.

Return Type:

  • Object: An object containing the average speed, stride, and heart rate values.

Example Return:

{
    speed: 5.2,
    stride: 0.8,
    heart_rate: 70
}

getValuesBetweenIndexes(data, current_index, previous_index, value)

This method accepts an array of data, a current_index, a previous_index, and a value, and returns an array of values between the current and previous indexes.

Arguments:

  • data (Array): An array of data.
  • current_index (Number): The current index.
  • previous_index (Number): The previous index.
  • value (String): The value to retrieve.

Return Type:

  • Array: An array of values between the current and previous indexes.

Example Return:

[3.4, 4.5, 3.8]

getSplitTime(data, pointers)

Calculates the split time (in seconds) between the first and second checkpoints in a given data array. If the split time cannot be calculated, null is returned.

Arguments

  • data (array): An array of data objects, where each object represents a record of information about a particular event or activity.
  • pointers (array): An array of checkpoint IDs, where each ID represents a specific checkpoint.

Returns

  • Returns a string representing the split time (in seconds) between the first and second checkpoints, rounded to two decimal places (e.g. "12.34"). If the split time cannot be calculated, null is returned.

Example Usage

const data = [
  { index: 1, device_time: 1654123456, checked_marker_id: "checkpoint1", distance: 1.23 },
  { index: 2, device_time: 1654126789, checked_marker_id: null, distance: 1.24 },
  { index: 3, device_time: 1654130123, checked_marker_id: "checkpoint2", distance: 1.25 },
  { index: 4, device_time: 1654133456, checked_marker_id: null, distance: 1.26 },
  { index: 5, device_time: 1654136789, checked_marker_id: null, distance: 1.27 },
  { index: 6, device_time: 1654140123, checked_marker_id: "checkpoint3", distance: 1.28 },
  { index: 7, device_time: 1654143456, checked_marker_id: null, distance: 1.29 }
];

const pointers = ["checkpoint1", "checkpoint2", "checkpoint3"];

const result = getSplitTime(data, pointers);
// Returns "34.67"

getAllCheckpoints(data)

Filters the given data array to return only the data objects that have a non-null checked_marker_id property, indicating that the data point represents a checkpoint.

Arguments

  • data (array): An array of data objects, where each object represents a record of information about a particular event or activity.

Returns

  • Returns an array of data objects, where each object has a non-null checked_marker_id property.

Example Return

[
  { index: 1, device_time: 1654123456, checked_marker_id: "checkpoint1", distance: 1.23 },
  { index: 3, device_time: 1654130123, checked_marker_id: "checkpoint2", distance: 1.25 },
  { index: 6, device_time: 1654140123, checked_marker_id: "checkpoint3", distance: 1.28 }
]

getFirstCheckpointIndex(checkpoints)

Returns the index of the first checkpoint in a given array of checkpoint data.

Arguments

  • checkpoints (array): An array of data objects representing checkpoints, where each object has a non-null checked_marker_id property.

Returns

  • Returns the index of the first checkpoint in the array.

Example Return

2

getPreviousCheckpointIndex(checkpoints)

Returns the index of the checkpoint immediately preceding the first checkpoint in a given array of checkpoint data.

Arguments

  • checkpoints (array): An array of data objects representing checkpoints, where each object has a non-null checked_marker_id property.

Returns

  • Returns the index of the checkpoint immediately preceding the first checkpoint in the array

getDistanceVariables(new_data, distance_variables, live_horse, speed_unit)

Description

This function takes in new data, distance variables, whether the horse is live or not, and the speed unit. It returns the updated distance variables based on the speed of the horse.

Parameters

  • new_data: Object - new data containing information about the horse's speed.
  • distance_variables: Object - an object containing the distance variables for the horse.
  • live_horse: Boolean - a flag that indicates whether the horse is live or not.
  • speed_unit: String - a string that represents the unit of speed.

Returns

  • distance_variables: Object - the updated distance variables for the horse.

convertCoordinatesToDD(data)

Description

This function takes in data containing the latitude and longitude of a location and returns the same data with the latitude and longitude converted to decimal degrees.

Parameters

  • data: Object - an object containing the latitude and longitude of a location.

Returns

  • current_data: Object - the updated data with the latitude and longitude converted to decimal degrees.

addLatencyVariables(data)

Description

This function takes in data and adds latency variables to it, which include the time difference between the device time, API endpoint time, and current time.

Parameters

  • data: Object - an object containing the data.

Returns

  • data: Object - the updated data with latency variables added.

getDelays(item)

Description

This function takes in an item containing latency information and returns a string that displays the device to API latency, API to APP latency, and overall latency.

Parameters

  • item: Object - an object containing latency information.

Returns

  • html: String - a string that displays the device to API latency, API to APP latency, and overall latency.

markCheckpoints(current_data, previous_data, pointers)

This method checks if the current data is a checkpoint. If it is, then the current_data object will be modified and three new properties will be added to it: is_checkpoint, checked_marker_name, and checked_marker_id. The method returns the modified current_data object.

Arguments:

  • current_data (Object): The current data object.
  • previous_data (Object): The previous data object.
  • pointers (Array): An array of objects containing information about pointers.

Return Type:

  • Object: The modified current_data object with the following additional properties:
    • is_checkpoint (Boolean): A flag indicating whether or not the current data object is a checkpoint.
    • checked_marker_name (String): The name of the marker that was checked if the current data object is a checkpoint.
    • checked_marker_id (String): The ID of the marker that was checked if the current data object is a checkpoint.

Example Usage:

const current_data = {
    xy_positions: {
        x: 10,
        y: 20
    }
};
const previous_data = {
    xy_positions: {
        x: 5,
        y: 10
    }
};
const pointers = [
    {
        list: [
            {
                xy_positions: {
                    x: 0,
                    y: 0
                }
            },
            {
                xy_positions: {
                    x: 20,
                    y: 20
                }
            }
        ],
        checkpoint_extension: 10,
        marker_id: 1,
        marker_name: 'Marker 1'
    }
];

const modified_current_data = markCheckpoints(current_data, previous_data, pointers);

console.log(modified_current_data);
// Output: {
//     xy_positions: {
//         x: 10,
//         y: 20
//     },
//     is_checkpoint: true,
//     checked_marker_name: 'Marker 1',
//     checked_marker_id: 1
// }

calculateIntersection(pointer_set, current_data, previous_data)

This method calculates the intersection point between two line segments defined by four points. The line segments are formed by the current and previous positions of an object, and the two positions of a pointer. If there is no intersection, the method returns null.

Checkpoint Calculations

In order to correctly identify exact timing of crossing a checkpoint, we use two pointers that are marked along the end of the race track. This gives us a straight line. The line crossing is calculated if the horse crosses this line.

To correctly identify line crossing we need to convert the latitude and longitude to cartesian co-ordinates (x-y co-ordinates).

Approximation for small areas

If the part of the surface of the earth which you want to draw is relatively small, then you can use a very simple approximation. You can simply use the horizontal axis x to denote longitude λ, the vertical axis y to denote latitude φ. The ratio between these should not be 1:1, though. Instead you should use cos(φ0) as the aspect ratio, where φ0 denotes a latitude close to the center of your map. Furthermore, to convert from angles (measured in radians) to lengths, you multiply by the radius of the earth (which in this model is assumed to be a sphere).

    x = r λ cos(φ0)
    y = r φ

This is simple equirectangular projection. In most cases, you'll be able to compute cos(φ0) only once, which makes subsequent computations of large numbers of points really cheap.

Calculation of φ0
φ0 = avg of lower and upper bounds of latitudes

To get lower and upper bounds we need two points across the map which is oriented north-south. The upper bound will be top-left corner and lower bound will be the bottom-right. The bounds must encompass the race course

NOTE: In our case since the difference between upper and lower bounds is very small, we do not need to find them for all maps. Hence, we are using constant values which are defined in the .env file

#MapConfigs
UPPER_LATITUDE=54.168405746780365
LOWER_LATITUDE=54.1664838041431

Arguments:

  • pointer_set (Object): An object that contains an array of pointers with their positions and a checkpoint extension value.
    • list (Array): An array of pointers, each pointer contains an object with an id and xy_positions properties.
    • checkpoint_extension (Number): A value that determines the extension length of the pointer bounds.
  • current_data (Object): An object that contains the current position of an object.
    • xy_positions (Object): An object containing the x and y coordinates of the position.
  • previous_data (Object): An object that contains the previous position of an object.
    • xy_positions (Object): An object containing the x and y coordinates of the position.

Return Type:

  • Object: An object representing the intersection point with the following properties:
    • x (Number): The x coordinate of the intersection point.
    • y (Number): The y coordinate of the intersection point.
  • null: If there is no intersection point.

Example Usage:

let pointer_set = {
  list: [
    {id: 1, xy_positions: {x: 10, y: 10}},
    {id: 2, xy_positions: {x: 50, y: 50}}
  ],
  checkpoint_extension: 5
}

let current_data = {
  xy_positions: {x: 30, y: 30}
}

let previous_data = {
  xy_positions: {x: 20, y: 20}
}

let intersection_point = this.calculateIntersection(pointer_set, current_data, previous_data);
if (intersection_point !== null) {
  console.log(`Intersection point: (${intersection_point.x}, ${intersection_point.y})`);
} else {
  console.log('No intersection point found.');
}

extendPointerBounds(p1, p2, extend_percent)

This method extends a line segment between two points p1 and p2 by a specified percentage of its length. The method returns an array of two points that represent the new extended segment.

Arguments:

  • p1 (Object): An object representing the first point with the properties x and y.
  • p2 (Object): An object representing the second point with the properties x and y.
  • extend_percent (Number): A number representing the percentage to extend the line segment by. If not specified, the method returns the original points.

Return Type:

  • Array: An array of two objects representing the new extended segment. Each object has the properties x and y.

Example Usage:

const p1 = { x: 0, y: 0 };
const p2 = { x: 5, y: 0 };
const extend_percent = 50;

const extended_segment = extendPointerBounds(p1, p2, extend_percent);

console.log(extended_segment);
// Output: [{ x: -2.5, y: 0 }, { x: 7.5, y: 0 }]

In the above example, the line segment between p1 and p2 is extended by 50% of its original length. The resulting extended segment is returned as an array of two points.

getExtendedPoint(primaryPoint, secondaryPoint, radius)

This method calculates the new point that lies on the circle centered at primaryPoint and having a radius of radius. The new point is determined by the intersection of the circle with the line segment between primaryPoint and secondaryPoint. The method returns an object representing the new point.

Arguments:

  • primaryPoint (Object): An object representing the center point of the circle with the properties x and y.
  • secondaryPoint (Object): An object representing the second point of the line segment with the properties x and y.
  • radius (Number): A number representing the radius of the circle.

Return Type:

  • Object: An object representing the new point with the properties x and y.

Example Usage:

const primaryPoint = { x: 0, y: 0 };
const secondaryPoint = { x: 5, y: 5 };
const radius = 10;

const new_point = getExtendedPoint(primaryPoint, secondaryPoint, radius);

console.log(new_point);
// Output: { x: 7.0710678118654755, y: 7.0710678118654755 }

isInBounds(p, p1, p2, is_extend=false)

This method checks if a point p is within the bounds of a rectangle defined by two points p1 and p2. Optionally, the bounds can be extended beyond the rectangle by setting the is_extend parameter to true.

Arguments:

  • p (Object): An object representing the point to check with the properties x and y.
  • p1 (Object): An object representing the first corner of the rectangle with the properties x and y.
  • p2 (Object): An object representing the opposite corner of the rectangle with the properties x and y.
  • is_extend (Boolean): An optional boolean indicating whether to extend the bounds beyond the rectangle. The default value is false.

Return Type:

  • Boolean: true if the point is within the bounds of the rectangle, false otherwise.

Example Usage:

const p = { x: 3, y: 4 };
const p1 = { x: 1, y: 1 };
const p2 = { x: 5, y: 5 };

const is_within_bounds = isInBounds(p, p1, p2);

console.log(is_within_bounds);
// Output: true

getDistanceInMeters(previous_data, current_data)

This method calculates the distance in meters between two geographic coordinates represented by previous_data and current_data. The method uses the haversine formula to calculate the great-circle distance between two points on a sphere.

Arguments:

  • previous_data (Object): An object representing the previous geographic coordinates. The object should have the properties parsed_coordinates.dd_longitude and parsed_coordinates.dd_latitude.
  • current_data (Object): An object representing the current geographic coordinates. The object should have the properties parsed_coordinates.dd_longitude and parsed_coordinates.dd_latitude.

Return Type:

  • Number: A number representing the distance in meters between the two geographic coordinates. Returns null if the distance calculation fails.

Example Usage:

const previous_data = { parsed_coordinates: { dd_longitude: -122.4194, dd_latitude: 37.7749 } };
const current_data = { parsed_coordinates: { dd_longitude: -73.935242, dd_latitude: 40.73061 } };

const distance_in_meters = getDistanceInMeters(previous_data, current_data);

console.log(distance_in_meters);
// Output: 4136087.4581357565

Note: The output value is subject to rounding errors and may vary slightly from the actual distance.

degreesToRadians(degrees)

This method converts an angle from degrees to radians.

Arguments:

  • degrees (Number): An angle in degrees.

Return Type:

  • Number: The angle converted to radians.

Example Usage:

const degrees = 180;
const radians = degreesToRadians(degrees);

console.log(radians);
// Output: 3.141592653589793

radiansToDegree(radians)

This method converts an angle from radians to degrees.

Arguments:

  • radians (Number): An angle in radians.

Return Type:

  • Number: The angle converted to degrees.

Example Usage:

const radians = 3.141592653589793;
const degrees = radiansToDegree(radians);

console.log(degrees);
// Output: 180

getAverageOfArray(array)

This method calculates the average value of an array of numbers.

Arguments:

  • array (Array): An array of numbers.

Return Type:

  • Number: The average value of the numbers in the array.

Example Usage:

const array = [1, 2, 3, 4, 5];
const average = getAverageOfArray(array);

console.log(average);
// Output: 3

roundToDecimals(value, decimal_precision=2)

This method rounds a given number value to a specified number of decimal places decimal_precision.

Arguments:

  • value (Number): A number to round.
  • decimal_precision (Number): The number of decimal places to round value to. If not specified, the default value is 2.

Return Type:

  • Number: The rounded number.

Example Usage:

const value = 3.141592;
const decimal_precision = 3;

const rounded_value = roundToDecimals(value, decimal_precision);

console.log(rounded_value);
// Output: 3.142

kmToMiles(value)

This method converts a distance value in kilometers to miles.

Arguments:

  • value (Number): A distance value in kilometers.

Return Type:

  • Number: The equivalent distance value in miles, rounded to 2 decimal places.

Example Usage:

const value = 10;

const miles = kmToMiles(value);

console.log(miles);
// Output: 6.21

milesToKm(value)

This method converts a distance value in miles to kilometers.

Arguments:

  • value (Number): A distance value in miles.

Return Type:

  • Number: The equivalent distance value in kilometers, rounded to 2 decimal places.

Example Usage:

const value = 6.21;

const km = milesToKm(value);

console.log(km);
// Output: 10

convertSpeed(speed, unit)

Converts the speed from one unit to another.

Parameters

  • speed - The speed value to be converted.
  • unit - The unit to convert the speed to.

Returns

  • The converted speed as a string rounded to 2 decimal places, or null if the input is invalid or the conversion is not possible.

Possible values for unit

  • 'meters_per_seconds'
  • 'km_per_hour'
  • 'meters_per_minute'
  • 'miles_per_hour'
  • 'minutes_per_km'
  • 'seconds_per_km'
  • 'seconds_per_200m'
  • 'seconds_per_400m'
  • 'seconds_per_8th_of_a_mile'
  • 'seconds_per_4th_of_a_mile'

Example usage

const convertedSpeed = convertSpeed(10, 'km_per_hour');
console.log(convertedSpeed); // Output: 2.78

getTimeDifference(start, end)

Calculates the time difference between two timestamps in seconds.

Parameters

  • start - The start timestamp as a string or Date object.
  • end - The end timestamp as a string or Date object.

Returns

  • The time difference in seconds as a string rounded to 2 decimal places, or null if the input is invalid.

Example usage

const start = '2022-01-01 00:00:00';
const end = '2022-01-01 00:01:30';
const timeDiff = getTimeDifference(start, end);
console.log(timeDiff); // Output: 90

getEpochTimeDifferenceInMilliseconds(start, end)

Calculates the time difference between two epoch timestamps in milliseconds.

Parameters

  • start - The start epoch timestamp.
  • end - The end epoch timestamp.

Returns

  • The time difference in milliseconds as a string rounded to 2 decimal places, or null if the input is invalid.

Example usage

const start = 1640995200; // January 1, 2022 00:00:00 (UTC)
const end = 1640995265; // January 1, 2022 00:01:05 (UTC)
const timeDiff = getEpochTimeDifferenceInMilliseconds(start, end);
console.log(timeDiff); // Output: 65000

toDSMLat(text)

This method converts a string representation of latitude coordinates in the format of degrees, minutes, seconds, and direction (N or S) into an object with separate properties for each component.

Parameters

  • text : string - A string representation of the latitude coordinates in the format of "ddmmssX", where "dd" represents the degrees, "mm" represents the minutes, "ss" represents the seconds, and "X" represents the direction (either "N" or "S").

Return value

  • An object with the following properties:
    • degree : number - The degree component of the latitude coordinates.
    • minutes : number - The minute component of the latitude coordinates.
    • seconds : number - The second component of the latitude coordinates.
    • direction : string - The direction component of the latitude coordinates ("N" or "S").

Example

const lat = "372853N";
const coordinates = toDSMLat(lat);
console.log(coordinates);
// Output: { degree: 37, minutes: 28, seconds: 53, direction: 'N' }

toDSMLng(text)

This method converts a string representation of longitude coordinates in the format of degrees, minutes, seconds, and direction (E or W) into an object with separate properties for each component.

Parameters

  • text : string - A string representation of the longitude coordinates in the format of "dddmmssX", where "ddd" represents the degrees, "mm" represents the minutes, "ss" represents the seconds, and "X" represents the direction (either "E" or "W").

Return value

  • An object with the following properties:
    • degree : number - The degree component of the longitude coordinates.
    • minutes : number - The minute component of the longitude coordinates.
    • seconds : number - The second component of the longitude coordinates.
    • direction : string - The direction component of the longitude coordinates ("E" or "W").

Example

const lng = "1221000W";
const coordinates = toDSMLng(lng);
console.log(coordinates);
// Output: { degree: 122, minutes: 10, seconds: 0, direction: 'W' }

parseDSMLat(text)

Converts a string representation of a latitude in DMS (degree-minute-second) format into a more readable format.

Parameters:

  • text : {String} - The string representation of the latitude in DMS format. It should be in the format DDMMSSS[N/S], where DD represents degrees, MM represents minutes, SSS represents seconds, and N/S represents the direction.

Returns:

  • {String} - The formatted string representation of the latitude.

Example:

let result = parseDSMLat("452648N");
console.log(result); // Output: "45° 26' 48.00" N"

parseDSMLng(text)

Converts a string representation of a longitude in DMS (degree-minute-second) format into a more readable format.

Parameters:

  • text : {String} - The string representation of the longitude in DMS format. It should be in the format DDDMMSSS[E/W], where DDD represents degrees, MM represents minutes, SSS represents seconds, and E/W represents the direction.

Returns:

  • {String} - The formatted string representation of the longitude.

Example:

let result = parseDSMLng("1221253W");
console.log(result); // Output: "122° 12' 53.00" W"

dmsToDdLat(text)

This method accepts a string representing a latitude in DMS format (degrees, minutes, seconds), and returns the latitude in decimal degrees (DD).

Arguments:

  • text (String): A string representing a latitude in DMS format.

Return Type:

  • Number: The latitude in decimal degrees.

Example Usage:

let result = this.dmsToDdLat('45° 30\' 30" N'); // 45.50833333

dmsToDdLng(text)

This method accepts a string representing a longitude in DMS format (degrees, minutes, seconds), and returns the longitude in decimal degrees (DD).

Arguments:

  • text (String): A string representing a longitude in DMS format.

Return Type:

  • Number: The longitude in decimal degrees.

Example Usage:

let result = this.dmsToDdLng('73° 45\' 0" W'); // -73.75

removeElementsAfterLimit(arr, limit)

This method accepts an array and a limit, and returns a new array with the same elements as the original array up to the limit.

Arguments:

  • arr (Array): The array to be limited.
  • limit (Number): The maximum number of elements to be returned.

Return Type:

  • Array: A new array with the same elements as the original array up to the limit.

Example Usage:

let result = this.removeElementsAfterLimit([1,2,3,4,5], 3); // [1,2,3]

latLngToGlobalXY(latitude, longitude, map_configs)

This method calculates the global X and Y coordinates of a location on the earth's surface, based on its latitude and longitude, using the following formulae:

λ = longitude
φ = latitude
r = earth radius
θ = avg of lower and upper bounds of latitudes
x = r * λ * cos(φ0)
y = r * φ

Arguments:

  • latitude (Number): The latitude of the location.
  • longitude (Number): The longitude of the location.
  • map_configs (Object): An object containing the configuration of the map. This object has the following properties:
    • UPPER_LATITUDE (Number): The upper bound of the latitude.
    • LOWER_LATITUDE (Number): The lower bound of the latitude.

Return Type:

  • Object: An object containing the global X and Y coordinates of the location. The object has the following properties:
    • x (Number): The global X coordinate of the location.
    • y (Number): The global Y coordinate of the location.

Example Usage:

const latitude = 51.5074;
const longitude = -0.1278;
const map_configs = {
  UPPER_LATITUDE: 90,
  LOWER_LATITUDE: -90,
};
const result = latLngToGlobalXY(latitude, longitude, map_configs);

console.log(result);
// Output: {x: -5667.42144, y: 6368.68085}

getDistanceBetweenTwoPoints(point1, point2)

This method calculates the distance between two points on a 2D plane, given their coordinates. The coordinates are represented as objects with x and y properties.

Arguments:

  • point1 (Object): An object representing the coordinates of the first point. The object has the following properties:
    • x (Number): The x-coordinate of the point.
    • y (Number): The y-coordinate of the point.
  • point2 (Object): An object representing the coordinates of the second point. The object has the following properties:
    • x (Number): The x-coordinate of the point.
    • y (Number): The y-coordinate of the point.

Return Type:

  • Number: The distance between the two points.

Example Usage:

const point1 = { x: 3, y: 4 };
const point2 = { x: 6, y: 8 };
const distance = getDistanceBetweenTwoPoints(point1, point2); // distance is 5

getSlopeFromPoints(point1, point2)

This method accepts two points and returns the slope of the line that passes through these two points.

Arguments:

  • point1 (Object): An object containing the x and y coordinates of the first point.
    • x (Number): The x-coordinate of the first point.
    • y (Number): The y-coordinate of the first point.
  • point2 (Object): An object containing the x and y coordinates of the second point.
    • x (Number): The x-coordinate of the second point.
    • y (Number): The y-coordinate of the second point.

Return Type:

  • Number: The slope of the line that passes through point1 and point2.

Example Return:

getSlopeFromPoints({x: 0, y: 0}, {x: 1, y: 1}); // returns 1

getIntersectionsOfLineAndCircle(p1, p2, radius)

This method accepts two points and a radius, and returns an array of points representing the intersection(s) between a line passing through the two points and a circle centered at the origin with the given radius.

Arguments:

  • p1 (Object): An object containing the x and y coordinates of the first point.
    • x (Number): The x-coordinate of the first point.
    • y (Number): The y-coordinate of the first point.
  • p2 (Object): An object containing the x and y coordinates of the second point.
    • x (Number): The x-coordinate of the second point.
    • y (Number): The y-coordinate of the second point.
  • radius (Number): The radius of the circle centered at the origin.

Return Type:

  • Array: An array of points representing the intersection(s) between the line passing through p1 and p2 and the circle centered at the origin with radius radius. Each point is an object containing the x and y coordinates of the intersection point.
    • x (Number): The x-coordinate of the intersection point.
    • y (Number): The y-coordinate of the intersection point.

Example Return:

getIntersectionsOfLineAndCircle({x: 0, y: 0}, {x: 1, y: 1}, 1); 
/* returns 
[
    {x: 0.7071067811865476, y: 0.7071067811865476},
    {x: -0.7071067811865476, y: -0.7071067811865476}
]
*/

signum(num)

This method accepts a number and returns -1 if the number is negative, 1 if it is positive, and 0 if it is zero.

Arguments:

  • num (Number): A number to check its sign.

Return Type:

  • Number: -1 if num is negative, 1 if it is positive, and 0 if it is zero.

Example Return:

signum(5); // returns 1
signum(-5); // returns -1
signum(0); // returns 0

getDiscriminant(r, dr, D)

This method calculates and returns the discriminant of a quadratic equation. The discriminant is calculated using the formula (r^2)*(dr^2) - D^2.

Arguments:

  • r (Number): A number that represents one of the coefficients of the quadratic equation.
  • dr (Number): A number that represents another coefficient of the quadratic equation.
  • D (Number): A number that represents the constant term of the quadratic equation.

Return Type:

  • Number: The discriminant of the quadratic equation.

Example Return:

getDiscriminant(2, 3, 4); // returns -23
getDiscriminant(1, -6, 9); // returns 0

checkPointExistsOnLine(p1, p2, p)

This method checks whether a point p lies on the line segment formed by two other points p1 and p2. It returns true if the point lies on the line segment, false otherwise.

Arguments:

  • p1 (Object): An object containing the x and y coordinates of the first point.
  • p2 (Object): An object containing the x and y coordinates of the second point.
  • p (Object): An object containing the x and y coordinates of the point to check.

Return Type:

  • Boolean: true if the point p lies on the line segment formed by p1 and p2, false otherwise.

Example Return:

const p1 = {x: 0, y: 0};
const p2 = {x: 4, y: 4};
const p3 = {x: 2, y: 2};
checkPointExistsOnLine(p1, p2, p3); // returns true

isBetweenLineSegment(point1, point2, point)

This method checks if a point is between two points that define a line segment. It returns a boolean value indicating whether the point lies on the line segment or not.

Arguments:

  • point1 (Object): An object containing the x and y coordinates of the first point.
  • point2 (Object): An object containing the x and y coordinates of the second point.
  • point (Object): An object containing the x and y coordinates of the point to be checked.

Return Type:

  • Boolean: Returns true if the point is on the line segment, false otherwise.

Example Usage:

const point1 = { x: 0, y: 0 };
const point2 = { x: 5, y: 5 };
const point3 = { x: 3, y: 3 };
const point4 = { x: 6, y: 6 };

console.log(isBetweenLineSegment(point1, point2, point3)); // true
console.log(isBetweenLineSegment(point1, point2, point4)); // false

formatTimeZonedUnixTime(timestamp, timezone='utc', format=null)

This method formats a Unix timestamp with a specified timezone and returns a formatted string. If a format is not provided, the method returns the timestamp in ISO format.

Arguments:

  • timestamp (Number): A Unix timestamp.
  • timezone (String): A string representing a valid timezone. Default value is 'utc'.
  • format (String): A string representing the format to be used. If null, the method returns the timestamp in ISO format.

Return Type:

  • String: A string representing the formatted timestamp.

Example Usage:

console.log(formatTimeZonedUnixTime(1621036800, 'America/New_York')); // "2021-05-15T00:00:00-04:00"
console.log(formatTimeZonedUnixTime(1621036800, 'Asia/Kolkata', 'MMM DD, YYYY')); // "May 15, 2021"

formatUnixTime(timestamp, format=null)

This method formats a Unix timestamp and returns a formatted string. If a format is not provided, the method returns the timestamp in ISO format.

Arguments:

  • timestamp (Number): A Unix timestamp.
  • format (String): A string representing the format to be used. If null, the method returns the timestamp in ISO format.

Return Type:

  • String: A string representing the formatted timestamp.

Example Usage:

console.log(formatUnixTime(1621036800)); // "2021-05-15T00:00:00Z"
console.log(formatUnixTime(1621036800, 'MMM DD, YYYY')); // "May 15, 2021"

timeDifferenceInSecondsUnix(started_at, ended_at)

This method calculates the time difference in seconds between two Unix timestamps.

Arguments:

  • started_at (Number): The Unix timestamp representing the start time.
  • ended_at (Number, optional): The Unix timestamp representing the end time. If not provided, the current time will be used as the end time.

Return Type:

  • Number: The time difference in seconds.

Example Usage:

const started_at = 1641683700; // January 9, 2022 8:35:00 AM UTC
const ended_at = 1641684000; // January 9, 2022 8:40:00 AM UTC
const timeDiff = timeDifferenceInSecondsUnix(started_at, ended_at);
console.log(timeDiff); // Output: 300

getParsedDeviceTime(unix_time, format)

This method accepts a Unix timestamp and returns a formatted string representing the time in the device's timezone.

Arguments:

  • unix_time (Number): The Unix timestamp to format.
  • format (String, optional): The format string for the output. Defaults to 'HH:mm:ss'.

Return Type:

  • String: The formatted time string.

Example Usage:

const unix_time = 1641683700; // January 9, 2022 8:35:00 AM UTC
const formattedTime = getParsedDeviceTime(unix_time, 'h:mm:ss a');
console.log(formattedTime); // Output: '3:35:00 am'

pad(num)

This method accepts a number and returns a string representation of the number with a leading zero if it is a single digit number.

Arguments:

  • num (Number): A number to be padded.

Return Type:

  • String: A string representation of the input number with a leading zero if it is a single digit number.

Example Return:

pad(5) // "05"
pad(10) // "10"

hhmmss(seconds, include_millis=true)

This method accepts a number of seconds and an optional boolean flag include_millis and returns a string representation of the time in the format hh:mm:ss.s, where s is an optional number of milliseconds.

Arguments:

  • seconds (Number): The number of seconds to be formatted.
  • include_millis (Boolean): An optional flag to include milliseconds in the formatted time. Defaults to true.

Return Type:

  • String: A string representation of the input time in the format hh:mm:ss.s, where s is an optional number of milliseconds.

Example Return:

hhmmss(65.123) // "00:01:05.123"
hhmmss(65.123, false) // "00:01:05"

Table of Contents