@gilbarbara/helpers

Collection of useful functions
Usage
npm i @gilbarbara/helpers
import { unique } from '@gilbarbara/helpers';
const password = unique(24, { includeSymbols: true });
console.log(password);
API
Arrays
quickSort<T extends string | number>(input: T[]): T[]
Sort an array of numbers using a quick sort algorithm.
sortByLocaleCompare(key?: string, options?: Intl.CollatorOptions & { descending?: boolean }): SortFunction
Returns a sort function with localeCompare comparison.
Type Definition
interface SortFunction<T = string> {
(left: Record<string, any>, right: Record<string, any>): number;
(left: T, right: T): number;
}
Example
const strings = ['Mãe', 'limão', 'cachê', 'tião', 'amô', 'côncavo'];
strings.sort(sortByLocaleCompare());
const objects = [{ key: 'réservé' }, { key: 'Premier' }, { key: 'Cliché' }, { key: 'communiqué' }, { key: 'café' }, { key: 'Adieu' }];
objects.sort(sortByLocaleCompare('key', { descending: true }));
sortByPrimitive<T extends number | boolean>(key?: string, descending?: boolean = false): SortFunction
Returns a sort function with primitive values comparison.
Type Definition
interface SortFunction<T = string> {
(left: Record<string, any>, right: Record<string, any>): number;
(left: T, right: T): number;
}
Example
const objects = [{ cycle: 3, status: true }, { cycle: 1, status: false }, { cycle: 3, status: true }, { cycle: 4, status: false }];
objects.sort(sortByPrimitive('status', true));
sortComparator(left: string | number, right: string | number): number
Basic sort comparator.
Async
cors(data: any, statusCode = 200, options?: CorsOptions): CorsOuput
Returns a CORSresponse.
Type Definition
type HttpMethods = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
interface CorsOptions {
headers?: string[];
methods?: HttpMethods[];
origin?: string;
}
interface CorsOuput {
body: string;
headers: Record<string, string>;
statusCode: number;
}
poll(condition: () => boolean, options?: PollOptions): Promise<void>
Awaits for the condition to be true based on the options.
Type Definition
interface PollOptions {
delay?: number;
maxRetries?: number;
}
request(url: string, options?: RequestOptions): Promise<any>
Perform an async request.
Type Definition
type HttpMethods = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
interface RequestOptions {
body?: any;
headers?: Record<string, any>;
method?: HttpMethods;
}
sleep(seconds?: number = 1): Promise<void>
Block async execution for X seconds.
Date
now(): number
Returns a unix timestamp (seconds since 1970-01-01 00:00 UTC).
timeSince(input: Date | string | number, options?: TimeSinceOptions): string
Returns how much time has passed since the input date.
You can change the locale with the options.
If the plural forms just adds an s
to the end, you don't need to pass it. It will add it automatically.
Type Definition
interface TimeSinceOptions {
day?: string;
days?: string;
hour?: string;
hours?: string;
minute?: string;
minutes?: string;
month?: string;
months?: string;
prefix?: string;
second?: string;
seconds?: string;
skipWeeks?: boolean;
suffix?: string;
week?: string;
weeks?: string;
year?: string;
years?: string;
}
Example
timeSince(twoDaysAgo)
timeSince(twoWeeksAgo, { skipWeeks: true })
timeSince(twoDaysAgo, { day: 'Tag', days: 'Tage', prefix: 'Vor', suffix:'' })
timeSince(twoWeeeksAgo, { suffix: 'atrás', week: 'semana' })
timestamp(input?: Date | string): number
Get the timestamp for a date
Misc
copyToClipboard(input: string): Promise<boolean>
Copy a string to the clipboard.
isRequired(input?: string = 'parameter', type: Constructable = TypeError): void
Throws an error of the Constructable type.
isJSON(input: string): boolean
Check if a string is a valid JSON.
Example
function exec(input: string = isRequired('input')) {}
exec()
function evaluate(input: string = isRequired('input', SyntaxError)) {}
exec()
logger(type: string, title: string, data: any, options?: LoggerOptions): void
Log grouped messages to the console.
Type Definition
interface LoggerOptions {
collapsed?: boolean;
hideTimestamp?: boolean;
skip?: boolean;
typeColor?: string;
}
noop(): void
An empty function that does nothing.
unique(length?: number = 8, options?: UniqueOptions): string
Returns a random string.
Type Definition
interface UniqueOptions {
includeLowercase?: boolean;
includeNumbers?: boolean;
includeSymbols?: boolean;
includeUppercase?: boolean;
}
uuid(): string
Returns an UUID v4 string.
Numbers
ceil(input: number, digits?: number = 2): number
Ceil decimal numbers.
floor(input: number, digits?: number = 2): number
Floor decimal numbers.
pad(input: number, digits?: number = 2): string
Pad a number with zeros.
randomInt(min?: number = 0, max?: number = 10): number
Returns a random integer.
round(input: number, digits?: number = 2): number
Round decimal numbers.
Objects
blacklist(input: Record<string, any>, ...filter)
Remove properties from an object.
invertKeys(input: Record<string, any>)
Invert object key and value
keyMirror(input: Record<string, any>)
Set the key as the value
queryStringFormat(input: Record<string, any>, options?: QueryStringFormatOptions)
Stringify a shallow object into a query string.
Type Definition
interface QueryStringFormatOptions {
addPrefix?: boolean;
encodeValuesOnly?: boolean;
encoder?: (uri: string) => string;
}
queryStringParse(input: string)
Parse a query string.
sortObjectKeys(input: Record<string, any>)
Sort object keys
Strings
capitalize(input: string): string
Capitalize the first letter.
cleanupHTML(input: string): string
Cleanup HTML content.
cleanupURI(input: string): string
Cleanup URI characters.
pluralize(singular: string, plural: string | undefined, quantity: number)
Returns the singular oor plural based on the quantity.
If the plural forms just adds an s
to the end, you don't need to pass it. It will add it automatically.
removeAccents(input: string): string
Remove accents.
removeEmojis(input: string): string
Remove emojis.
removeEmptyTags(input: string): string
Remove empty HTML Tags (including whitespace).
removeNonPrintableCharacters(input: string): string
Remove non-printable ASCII characters.
removeTags(input: string): string
Remove HTML tags.
removeWhitespace(input: string): string
Remove whitespace.
slugify(input: string): string
Format string to slug.