# Helpers
## arrayToDistinct
Returns an Array of objects that are distinct based on the specified key. Higher indices override lower indices in the array.
### Parameters
- `objects`: An array of objects that should become distinct.
- `getKey`: A function that determines which attribute should be the identifier for distinct objects.
- Type: `(obj: T) => string`
- `filter` (optional): A function to filter objects before considering them for distinctness.
- Type: `(obj: T) => boolean`
### Returns
Returns an array with distinct objects determined by the `getKey` function.
### Example
```javascript
const arr = [
{
person: { name: "max", id: "0" },
job: { title: "Developer" },
},
{
person: { name: "tim", id: "1" },
job: { title: "Developer" },
},
{
person: { name: "max", id: "0" },
job: { title: "Project Manager" },
},
];
console.log(arrayToDistinct(arr, (obj) => obj.person.id));
```
## arrayToTree
Converts an array to a new tree-like array, where objects are assigned a new "children" attribute.
### Parameters
- `objects`: The array from which a tree-like copy should be created.
- `getParentKey`: A function to retrieve the parent key from each object.
- Type: `(object: T) => any`
- `getIdentifier`: A function to retrieve the identifier of an object.
- Type: `(object: T) => any`
### Returns
A new tree-like array with new objects.
### Example
```javascript
const arr = [
{
someAttributes: "",
weirdId: "hEHIec",
weirdParent: "12345",
},
{
someAttributes: "",
weirdId: "12345",
weirdParent: undefined,
},
];
const newHierarchyArray = arrayToTree(
arr,
(obj) => obj.weirdParent,
(obj) => obj.weirdId
);
```
## treeToArray
Converts any hierarchy-array to a flat array without altering the original array.
### Parameters
- `objects`: The hierarchy array to be flattened.
- `getChildren`: A getter function to retrieve the attribute where the children are stored.
- Type: `(obj: T) => Array<T>`
### Returns
A flat array containing all objects of the hierarchy array.
### Example
```javascript
const flatArray = treeToArray(newHierarchyArray, (obj) => obj.children);
```
## compare
Compares two values using a mapper function and returns a comparator function suitable for sorting arrays.
### Parameters
- `mapper`: A function to transform the values before comparison.
- `desc` (optional): A boolean indicating whether to sort in descending order (default is ascending order).
### Returns
A comparator function suitable for sorting arrays.
### Example
```javascript
const sortedArray = myArray.sort(compare((item) => item.property));
```
## copy
Creates a deep copy of the provided object using JSON serialization and deserialization.
### Parameters
- `a`: The object to be copied.
### Returns
A deep copy of the provided object.
### Example
```javascript
const originalObject = { key: "value", nested: { key: "nested value" } };
const copiedObject = copy(originalObject);
```
## createInternalComponent
Creates an internal React component by returning the provided function component.
### Parameters
- `component`: The function component to be returned as an internal component.
### Returns
A React function component.
### Example
```jsx
import React from "react";
const MyComponent: React.FC<Props> = ({ prop1, prop2 }) => {
// Component implementation...
};
const InternalComponent = createInternalComponent(MyComponent);
```
## Date Helpers
### Enums
#### TimeMode
Defines modes for handling time.
##### Members:
- `DurationMode`: Represents the mode for dealing with durations.
- Value: `0`
- Description: This mode is used when working with time durations, such as calculating differences between two timestamps or representing a duration in various units (e.g., hours, minutes, seconds).
- `DateMode`: Represents the mode for working with specific dates and times.
- Value: `1`
- Description: This mode is used when working with specific dates and times, such as formatting timestamps, parsing date strings, or obtaining information about a specific date (e.g., day of the week, month, year).
#### TimeDisplayMode
Defines display modes for time.
##### Members:
- `DurationMode`: Represents the mode for displaying time durations.
- Value: `0`
- Description: This mode is used when displaying time durations in various formats, such as full duration strings, abbreviated units, or human-readable formats like "3 hours ago".
- `DateMode`: Represents the mode for displaying specific dates and times.
- Value: `1`
- Description: This mode is used when displaying specific dates and times in various formats, such as full date and time strings, date-only or time-only formats, or human-readable formats like "today" or "yesterday".
### Utility Functions
#### isDateUnit
Checks if the provided unit is a valid date unit.
#### getTimeString
Generates a formatted time string based on the provided parameters.
##### Parameters:
- `tMode`: Time mode (DurationMode or DateMode).
- `timeDisplay`: Display mode for time (full, unit, humanize, unix).
- `unit`: Unit of time (e.g., seconds, minutes, hours).
- `cValue`: Value to be formatted.
#### isSecondsUnit, isMillisecondsUnit, isMinutesUnit, isHoursUnit, isDaysUnit, isWeeksUnit, isMonthUnit, isYearsUnit
Checks if the provided unit corresponds to a specific unit of time.
## downloadCSV
Downloads a CSV file with the provided filename and content.
### Parameters
- `filename`: The filename for the downloaded CSV file.
- Type: `string`
- `csv`: The content of the CSV file as a string.
- Type: `string`
### Example
```javascript
const filename = "example.csv";
const csvContent = "Name, Age\nJohn, 30\nDoe, 25";
downloadCSV(filename, csvContent);
```
## downloadDataUrl
Downloads data from a given Data URL by creating a temporary anchor element and simulating a click.
### Parameters
- `filename`: The filename for the downloaded file.
- Type: `string`
- `dataUrl`: The Data URL containing the data to be downloaded.
- Type: `string`
### Example
```javascript
const filename = "example.txt";
const dataUrl = "data:text/plain;charset=utf-8;base64,SGVsbG8gV29ybGQh";
downloadDataUrl(filename, dataUrl);
```
## equals
Compares two values deeply to determine if they are equivalent.
### Parameters
- `a`: The first value to compare.
- `b`: The second value to compare.
### Returns
A boolean value indicating whether the two values are equivalent (`true`) or not (`false`).
### Example
```javascript
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };
console.log(equals(obj1, obj2)); // Output: true
```
## formatDistance
Formats a distance measurement in millimeters into a human-readable string representation.
### Parameters
- `mm`: The distance measurement in millimeters.
- Type: `number`
### Returns
A string representing the formatted distance.
### Example
```javascript
console.log(formatDistance(1234)); // Output: "1m"
console.log(formatDistance(5000)); // Output: "5m"
console.log(formatDistance(10000)); // Output: "10m"
console.log(formatDistance(15000)); // Output: "15m"
console.log(formatDistance(100000)); // Output: "100m"
console.log(formatDistance(150000)); // Output: "0.15km"
console.log(formatDistance(500000)); // Output: "0.5km"
console.log(formatDistance(1000000)); // Output: "1km"
console.log(formatDistance(1500000)); // Output: "2km"
```
## formatFileSize
Formats a file size measurement in bytes into a human-readable string representation.
### Parameters
- `bytes`: The file size measurement in bytes.
- Type: `number`
### Returns
A string representing the formatted file size.
### Example
```javascript
console.log(formatFileSize(1234)); // Output: "1234B"
console.log(formatFileSize(5000)); // Output: "5KB"
console.log(formatFileSize(10000)); // Output: "10KB"
console.log(formatFileSize(15000)); // Output: "15KB"
console.log(formatFileSize(100000)); // Output: "100KB"
console.log(formatFileSize(1500000)); // Output: "1MB"
console.log(formatFileSize(5000000)); // Output: "5MB"
console.log(formatFileSize(10000000)); // Output: "10MB"
console.log(formatFileSize(150000000)); // Output: "150MB"
console.log(formatFileSize(1000000000)); // Output: "1GB"
console.log(formatFileSize(15000000000)); // Output: "15GB"
console.log(formatFileSize(100000000000)); // Output: "100GB"
console.log(formatFileSize(1500000000000)); // Output: "1TB"
console.log(formatFileSize(5000000000000)); // Output: "5TB"
```
## formatRelativeDates
Formats relative dates from a given date or timestamp to the current date or timestamp.
### Parameters
- `from`: The starting date or timestamp.
- Type: `Date | number`
- `to`: The ending date or timestamp (optional). Defaults to the current date or timestamp.
- Type: `Date | number`
- Default: `Date.now()`
### Returns
A string representing the formatted relative date.
### Example
```javascript
const from = new Date("2022-01-01");
const to = new Date("2022-01-10");
console.log(formatRelativeDates(from, to)); // Output: "in 9 days"
```
## safeStringEncode
Encodes a string into a base-64 encoded string.
### Parameters
- `str`: The string to encode.
- Type: `string`
### Returns
A base-64 encoded string representing the input string.
### Example
```javascript
const encodedString = safeStringEncode("Hello, World!");
console.log(encodedString); // Output: "SGVsbG8sIFdvcmxkIQ=="
```
## safeStringDecode
Decodes a base-64 encoded string into its original string representation.
### Parameters
- `str`: The base-64 encoded string to decode.
- Type: `string`
### Returns
The original string decoded from the input base-64 encoded string.
### Example
```javascript
const decodedString = safeStringDecode("SGVsbG8sIFdvcmxkIQ==");
console.log(decodedString); // Output: "Hello, World!"
```
## timeSelectUnit
This function calculates the time difference between two dates and returns the appropriate unit along with the rounded value.
### Parameters
- `from` (Date | number): The starting date or timestamp.
- `to` (Date | number): The ending date or timestamp. Defaults to the current date if not provided.
### Returns
- Returns an array containing two elements:
- Rounded value of the time difference.
- Unit of time (`"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`).
### Example
```javascript
import { timeSelectUnit } from "./your-helper-file";
const from = new Date("2024-05-01");
const to = new Date("2024-05-07");
const [value, unit] = timeSelectUnit(from, to);
console.log(`The time difference is approximately ${value} ${unit}(s)`);
```
## urlBase64ToUint8Array
This function converts a base64 string to a Uint8Array, primarily used by the user service to obtain a WebPush Subscription.
This function is necessary because Chrome doesn't accept a base64 encoded string as the value for `applicationServerKey` in `pushManager.subscribe` yet. (Refer: [Chrome Bug](https://bugs.chromium.org/p/chromium/issues/detail?id=802280))
### Parameters
- `base64String` (string): The base64 encoded string to be converted.
### Return
- Returns a Uint8Array containing the decoded data.
### Example
```javascript
import { urlBase64ToUint8Array } from "./your-helper-file";
const base64String = "your_base64_string_here";
const uint8Array = urlBase64ToUint8Array(base64String);
console.log(uint8Array);
```
## uuid
This function generates a universally unique identifier (UUID).
This function generates a UUID using a simple algorithm based on bitwise operations and random numbers.
### Parameters
- `a` (optional): The version of the UUID. If provided, it must be a number.
### Return
- Returns a string representing the generated UUID.
### Example
```javascript
import { uuid } from "./your-helper-file";
// Generate a UUID without specifying a version
const generatedUUID = uuid();
console.log(generatedUUID);
// Generate a UUID specifying a version (e.g., version 4)
const version4UUID = uuid(4);
console.log(version4UUID);
```