Documentation
File: Helpers.js
Description: This file contains a collection of utility functions used for various tasks within the application. These helpers provide common functionality that can be reused across different components and modules, reducing code duplication and promoting consistency.
Constants
N_LOG_HISTORY
: A constant defining the number of days of log history to be kept.IP_SERVICE
: A constant holding the URL of the IP service used for obtaining user's location information.PipeStatus
: An enum representing different statuses of a pipe, defining states like "REGISTERED", "QUEUED", "IN_PROGRESS", "SKIPPED", "STOPPED", "COMPLETED", "FAILED".DESKTOP_WIDTH_THRESH
: A constant defining the maximum width in pixels to consider a device a desktop.
Functions
Function: loadConfig
Description: This function asynchronously loads configuration details from the backend, including supported languages, A/B test configurations, and other relevant data.
Parameters: None
Returns: void
Example:
loadConfig(); // Loads the configuration details
Function: getSupportedDisplay
Description: Retrieves an array of supported display languages.
Parameters: None
Returns: Array<string>
: An array of strings representing supported display languages.
Example:
const supportedDisplays = getSupportedDisplay();
console.log(supportedDisplays); // Logs the array of supported display languages
Function: getSlug
Description: Returns the slug associated with a given extension.
Parameters:
extension
(string
): The extension for which to retrieve the slug.
Returns: string
: The slug for the provided extension, or "unk" if not found.
Example:
const slug = getSlug("js"); // Retrieves the slug for the "js" extension
console.log(slug); // Logs the slug
Function: isSupported
Description: Checks if a file is supported by the application based on its extension.
Parameters:
file
(object
): The file object to check.
Returns: boolean
: True if the file extension is supported, false otherwise.
Example:
const file = { path: "myFile.txt" };
const isSupportedFile = isSupported(file);
console.log(isSupportedFile); // Logs whether the file is supported
Function: getHubSupported
Description: Returns an array of languages supported for documentation purposes.
Parameters: None
Returns: Array<string>
: An array of strings representing languages supported for documentation.
Example:
const hubSupportedLanguages = getHubSupported();
console.log(hubSupportedLanguages); // Logs the array of supported documentation languages
Function: random
Description: Returns a random item from the provided array.
Parameters:
arr
(Array<any>
): The array from which to select a random item.
Returns: any
: A randomly selected item from the array.
Example:
const numbers = [1, 2, 3, 4, 5];
const randomNum = random(numbers);
console.log(randomNum); // Logs a random number from the array
Function: redirect
Description: Redirects the user to a specified path.
Parameters:
path
(string
): The path to redirect to. Default: "/"external
(boolean
): Whether to open the path in a new tab or window. Default:false
Returns: void
Example:
redirect("/login"); // Redirects to the login page
redirect("https://www.google.com", true); // Opens Google in a new tab
Function: orderBranches
Description: Rearranges the branches in an array, ensuring the default branch is placed at the beginning of the list.
Parameters:
branches
(Array<object>
): The array of branches to be ordered.default_branch
(string
): The name of the default branch.
Returns: Array<object>
: The reordered array of branches.
Example:
const branches = [{ name: "branch2" }, { name: "branch1" }, { name: "branch3" }];
const orderedBranches = orderBranches({ branches, default_branch: "branch1" });
console.log(orderedBranches); // Logs the branches with "branch1" at the beginning
Function: getProviders
Description: Extracts an array of provider names from a user's account information.
Parameters:
user
(object
): The user object containing account details.
Returns: Array<string>
: An array of strings representing provider names.
Example:
const user = { accounts: [{ provider: "Google" }, { provider: "Facebook" }] };
const providers = getProviders(user);
console.log(providers); // Logs the providers: ["Google", "Facebook"]
Function: isGithubInstallation
Description: Checks if the current page is a Github installation page and returns the installation details.
Parameters: None
Returns: object
: An object containing the installation details if it's a Github installation page, otherwise returns an empty object.
Example:
const installationDetails = isGithubInstallation();
if (installationDetails.installation_id) {
console.log("This is a Github Installation page");
}
Function: cleanQuery
Description: Removes all query parameters from the current URL and returns the new search and hash values.
Parameters: None
Returns: object
: An object with two properties:
search
: A string representing the cleaned query string.hash
: A string representing the hash part of the URL.
Example:
const cleanedUrl = cleanQuery();
window.location.search = cleanedUrl.search; // Update the URL with the cleaned query
Function: checkPaymentSession
Description: Retrieves the "session_id" from the current URL query parameters.
Parameters: None
Returns: string
: The value of the "session_id" query parameter, or null if not found.
Example:
const sessionId = checkPaymentSession();
console.log(sessionId); // Logs the session ID, or null if not present.
Function: getPipeStatus
Description: Renders a visual representation of the status of a pipe based on its status
property.
Parameters:
pipe
(object
): The pipe object containing the status information.onClick
(function
): A function to be executed when the question mark icon is clicked.
Returns: JSX.Element
: A JSX element representing the pipe status with appropriate visual styling and icons.
Example:
const pipe = { status: PipeStatus.QUEUED };
const handleQuestionClick = () => { console.log("Question mark clicked!"); };
const pipeStatusElement = getPipeStatus(pipe, handleQuestionClick);
Function: enumToStr
Description: Returns the string key associated with a given value in an enum.
Parameters:
obj
: The enum object.status
: The enum value for which to find the corresponding key.
Returns: string
: The string key representing the enum value, or undefined if not found.
Example:
const status = PipeStatus.QUEUED;
const statusKey = enumToStr(PipeStatus, status);
console.log(statusKey); // Logs "QUEUED"
Function: _merge
Description: Merges two arrays by replacing elements in the first array with corresponding elements from the second array based on their values.
Parameters:
arr
: The array to be modified.old
: The array containing values to be replaced.neww
: The array containing new values to replace the old values.
Returns: Array<any>
: The modified array with elements replaced based on the merge operation.
Example:
const arr = ["a", "b", "c"];
const old = ["b", "c"];
const neww = ["d", "e"];
const mergedArr = _merge(arr, old, neww);
console.log(mergedArr); // Logs ["a", "d", "e"]
Function: getLogos
Description: Generates an array of ReactSVG elements representing logos for a set of languages, optionally applying color styling.
Parameters:
languages
(Array<string>
): An array of language names or slugs.colored
(boolean
): Whether to apply color styling to the logos. Default:true
Returns: Array<JSX.Element>
: An array of ReactSVG elements representing the logos for the given languages.
Example:
const languages = ["en", "fr", "es"];
const logos = getLogos(languages, false); // Generates logos without color
Function: getDuration
Description: Calculates the duration between a start time and either a finish time or updated time.
Parameters:
pipe
(object
): The pipe object containingstarted_at
,finished_at
, andupdated_at
timestamps.exact
(boolean
): Whether to return the exact duration in seconds, or a human-readable relative duration. Default:false
Returns: string
or number
: A human-readable relative duration or the exact duration in seconds.
Example:
const pipe = { started_at: "2023-10-26T10:00:00", finished_at: "2023-10-26T10:15:00" };
const duration = getDuration(pipe); // Returns "15 minutes ago"
const exactDuration = getDuration(pipe, true); // Returns 900 (seconds)
Function: extractOriginalBranch
Description: Extracts the original branch name from a branch name that might contain prefixes or suffixes related to comments.
Parameters:
branch
(string
): The branch name to extract the original branch from.
Returns: string
: The original branch name.
Example:
const branch = "komment-123456";
const originalBranch = extractOriginalBranch(branch);
console.log(originalBranch); // Logs "123456"
Function: formatTime
Description: Formats a date and time string into a specific format.
Parameters:
dt
(string
): The date and time string to format.
Returns: string
: The formatted date and time string.
Example:
const dt = "2023-10-26T10:00:00";
const formattedTime = formatTime(dt);
console.log(formattedTime); // Logs "2023-10-26 10:00:00"
Function: delay
Description: Delays the execution of a promise for a specified duration.
Parameters:
time
(number
): The duration in milliseconds to delay. Default: 500ms.
Returns: Promise<void>
: A promise that resolves after the specified delay.
Example:
delay(1000).then(() => {
console.log("Delayed execution after 1 second");
});
Function: now
Description: Returns the current Unix timestamp.
Parameters: None
Returns: number
: The current Unix timestamp.
Example:
const timestamp = now();
console.log(timestamp); // Logs the current Unix timestamp
Function: sort
Description: Sorts an array of objects based on a specified key, with an optional parameter to reverse the sorting order.
Parameters:
arr
(Array<object>
): The array to be sorted.key
(string
): The key to sort by.rev
(boolean
): Whether to reverse the sorting order. Default:false
Returns: Array<object>
: The sorted array.
Example:
const items = [{ name: "apple" }, { name: "banana" }, { name: "cherry" }];
const sortedItems = sort(items, "name"); // Sorts alphabetically
const reversedItems = sort(items, "name", true); // Sorts alphabetically in reverse
Function: divide
Description: Divides an array into sub-arrays of a specified quantity, optionally extracting a specific key from each object.
Parameters:
arr
(Array<any>
): The array to divide.quantity
(number
): The desired quantity of elements in each sub-array.key
(string
): The key to extract from each object. Default:null
Returns: Array<Array<any>>
: An array containing sub-arrays of the specified quantity.
Example:
const items = [1, 2, 3, 4, 5, 6];
const dividedItems = divide(items, 2);
console.log(dividedItems); // Logs [[1, 2], [3, 4], [5, 6]]
const objects = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }];
const dividedObjects = divide(objects, 2, "name");
console.log(dividedObjects); // Logs [["A", "B"], ["C"]]
Function: cutoffDate
Description: Calculates a date in the past based on the N_LOG_HISTORY
constant and returns it in ISO format.
Parameters: None
Returns: string
: The calculated date in ISO format.
Example:
const cutoffDate = cutoffDate();
console.log(cutoffDate); // Logs a date N_LOG_HISTORY days in the past
Function: shortId
Description: Generates a shortened ID from a given UUID by taking the first 7 characters.
Parameters:
uuid
(string
): The UUID to shorten.
Returns: string
: The shortened ID, or null if the UUID is empty.
Example:
const uuid = "12345678-1234-1234-1234-1234567890ab";
const shortId = shortId(uuid);
console.log(shortId); // Logs "1234567"
Function: randomItem
Description: Selects a random item from an array, including its index.
Parameters:
array
(Array<any>
): The array to choose a random item from.
Returns: object
: An object containing the random item and its index.
Example:
const items = [{ id: 1 }, { id: 2 }, { id: 3 }];
const randomItem = randomItem(items);
console.log(randomItem); // Logs a random item from the array and its index.
Function: getLocation
Description: Asynchronously retrieves the user's location information from an IP service.
Parameters: None
Returns: Promise<object>
: A promise that resolves to an object containing the user's city and country information.
Throws:
Error
: If there is an error fetching the location data from the IP service.
Example:
getLocation().then((location) => {
console.log(location); // Logs the user's location
}).catch((error) => {
console.error("Error getting location:", error);
});
Function: getMonthYear
Description: Formats a date string into a month and year format.
Parameters:
date
(string
): The date string to format.
Returns: string
: The formatted date string in month and year format (e.g., "Jan '23").
Example:
const date = "2023-01-15";
const monthYear = getMonthYear(date);
console.log(monthYear); // Logs "Jan '23"
Function: getTime
Description: Converts a time value in specified units into an object containing hours and minutes.
Parameters:
time
(number
): The time value.unit
(string
): The unit of the time value. Default: "minutes".
Returns: object
: An object with two properties:
hours
: The number of hours.minutes
: The number of minutes.
Example:
const time = 120; // 120 minutes
const duration = getTime(time);
console.log(duration); // Logs { hours: 2, minutes: 0 }
const timeInHours = 3;
const durationInHours = getTime(timeInHours, "hours");
console.log(durationInHours); // Logs { hours: 3, minutes: 0 }
Function: formatDate
Description: Formats a date string into a more readable format.
Parameters:
date
(string
): The date string to format.
Returns: string
: The formatted date string (e.g., "Jan 15, 2023").
Example:
const date = "2023-01-15";
const formattedDate = formatDate(date);
console.log(formattedDate); // Logs "Jan 15, 2023"
Function: formatMoney
Description: Formats a numerical value into a currency string with optional compact notation and display options.
Parameters:
value
(number
): The numerical value to format.format
(string
): The display format for compact notation. Default: "long".locale
(string
): The locale to use for formatting. Default: "en-US".
Returns: string
: The formatted currency string.
Example:
const value = 1234567.89;
const formattedMoney = formatMoney(value); // Logs "1.2M"
const formattedMoneyShort = formatMoney(value, "short"); // Logs "1.2M"
const formattedMoneyLong = formatMoney(value, "long"); // Logs "1.2 million"
Function: encode
Description: Encodes an object into a Base64 string.
Parameters:
source
(object
): The object to encode.
Returns: string
: The Base64 encoded string.
Example:
const obj = { name: "John", age: 30 };
const encodedObj = encode(obj);
console.log(encodedObj); // Logs the Base64 encoded string
Function: decode
Description: Decodes a Base64 string into an object.
Parameters:
state
(string
): The Base64 encoded string to decode.
Returns: object
: The decoded object, or an empty object if decoding fails.
Example:
const encodedObj = "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9"; // Example Base64 string
const decodedObj = decode(encodedObj);
console.log(decodedObj); // Logs { name: "John", age: 30 }
Function: capitalize
Description: Capitalizes the first letter of a string.
Parameters:
str
(string
): The string to capitalize.
Returns: string
: The capitalized string.
Example:
const str = "hello world";
const capitalizedStr = capitalize(str);
console.log(capitalizedStr); // Logs "Hello world"
Function: isDesktop
Description: Checks if the current device is a desktop based on the DESKTOP_WIDTH_THRESH
constant.
Parameters: None
Returns: boolean
: True if the device is a desktop, false otherwise.
Example:
const isDesktopDevice = isDesktop();
if (isDesktopDevice) {
console.log("This is a desktop device");
}
Function: supportedLanguages
Description: Checks if there are any languages supported for documentation purposes based on the provided languages
object.
Parameters:
languages
(object
): An object containing language information. Default:{}
Returns: boolean
: True if there are supported languages, false otherwise.
Example:
const languages = { en: "English", es: "Spanish" };
const hasSupportedLanguages = supportedLanguages(languages);
console.log(hasSupportedLanguages); // Logs whether there are supported languages.