Skip to content

Class: Utils

Utils - A collection of general-purpose utility functions.

Author

Heliomar P. Marques https://navto.me/heliomarpm

Other

sortByProps()

ts
static sortByProps(properties): (objA, objB) => number;

Parameters

properties

string | string[]

Returns

ts
(objA, objB): number;
Parameters
objA

Record<string, unknown>

objB

Record<string, unknown>

Returns

number

Deprecated

Use Utils.sortBy instead

Utils.chunk

chunk()

ts
static chunk: <T>(arr, size) => T[][];

Divide an array into smaller chunks of a specified size.

Type Parameters

T

T

Parameters

arr

T[]

The array to chunk.

size

number

The size of each chunk.

Returns

T[][]

An array of chunks.

Example

ts
const arr = [1, 2, 3, 4, 5];
const chunks = Utils.chunk(arr, 2);
console.log(chunks); // [[1, 2], [3, 4], [5]]

Utils.clamp

clamp()

ts
static clamp: (num, min, max) => number;

Clamps a number between a minimum and maximum value.

Parameters

num

number

The number to clamp.

min

number

The minimum value.

max

number

The maximum value.

Returns

number

The clamped number.

Example

ts
const clampedValue = Utils.clamp(10, 1, 5);
console.log(clampedValue); // Outputs: 5

Utils.compose

compose()

ts
static compose: <T, R>(...fns) => (arg) => R;

Composes multiple unary functions from right to left. Ensures type safety between function outputs and inputs

Type Parameters

T

T extends unknown[]

R

R

Parameters

fns

...{ [K in string | number | symbol]: Fn<any, any> }

An array of functions to be composed.

Returns

A function that takes a single argument and processes it through the composed sequence of functions.

ts
(arg): R;
Parameters
arg

T[0]

Returns

R

Throws

Will throw an error if no functions are provided or if any argument is not a function.

Example

ts
const addOne = (x: number) => x + 1;
const numToString = (x: number) => String(x);
const length = (s: string) => s.length;

const process = Utils.compose(length, numToString, addOne);
console.log(process(5)); // 1

Utils.crypto

crypto

crypto

ts
static crypto: object;

Namespace

A set of cryptographic utility functions for key generation, encryption, and decryption using the Web Crypto API.

decrypt()

ts
decrypt(encryptedText, key): Promise<string>;

Decodes a Base64 string and decrypts the contents using the AES-GCM algorithm.

Parameters
encryptedText

string

The Base64 string to decrypt.

key

CryptoKey

The CryptoKey used for decryption.

Returns

Promise<string>

The decrypted string.

Example
ts
const key = await generateKey();
const encrypted = await encrypt("Hello, World!", key);
const decrypted = await decrypt(encrypted, key);
console.log(decrypted);

encrypt()

ts
encrypt(text, key): Promise<string>;

Encrypts a string using AES-GCM algorithm and returns the result as a Base64 string.

Parameters
text

string

The plaintext string to encrypt.

key

CryptoKey

The CryptoKey used for encryption.

Returns

Promise<string>

A Promise that resolves to the encrypted Base64 string.

Example
ts
const key = await generateKey();
const encrypted = await encrypt("Hello, World!", key);
console.log(encrypted);

#### generateKey()

```ts
generateKey(): Promise<CryptoKey>;

Generates a new 256-bit AES-GCM key.

Returns

Promise<CryptoKey>

A Promise that resolves to a CryptoKey that can be used for encryption and decryption.

Example
ts
const key = await generateKey();

Utils.dayOfYear

dayOfYear()

ts
static dayOfYear: (input?) => number;

Returns the day of the year (1-365) (ISO 8601)

Parameters

input?

The date to get the day of the year for.

string | number | Date

Returns

number

The day of the year (1-365).

Example

ts
const today = new Date();
const dayOfYear = Utils.dayOfYear(today);
console.log(dayOfYear); // 1-365

Utils.debounce

debounce()

ts
static debounce: <T>(fn, wait) => T;

Creates a debounced version of the given function. Debouncing is a technique for optimizing performance by delaying the execution of a function until a specified delay has passed since the last time it was called.

Type Parameters

T

T extends (...args) => unknown

Parameters

fn

T

The function to debounce.

wait

number

The delay in milliseconds.

Returns

T

A debounced version of the function.

Example

ts
const add = (a: number, b: number) => a + b;
const debouncedAdd = debounce(add, 500);

debouncedAdd(1, 2); // Calls the function immediately
debouncedAdd(3, 4); // Calls the function after 500ms

const debouncedSearch = debounce(searchFunction, 300);
input.addEventListener('input', debouncedSearch);

Utils.deepOmit

deepOmit()

ts
static deepOmit: <T>(obj, paths) => Partial<T>;

Creates a new object by omitting specified paths from the original object.

Type Parameters

T

T extends Record<string, unknown>

Parameters

obj

T

The source object.

paths

readonly string[]

An array of paths to omit from the source object.

Returns

Partial<T>

A new object containing all key-value pairs except the omitted paths.

Example

ts
const user = { id: 1, name: 'John', age: 34, childs: [ {name: 'John II', age: 10 }, { name: 'Jane II', age: 8 }, { name: 'dog', age: 2 } ]  };

const omittedDog = Utils.deepOmit(user, ['id', 'age', 'childs.2']);
console.log(omittedDog); // { name: 'John', childs: [ {name: 'John II', age: 10 }, { name: 'Jane II', age: 8 } ] }

const omittedProps = Utils.deepOmit(user, ['id', 'age', 'childs']);
console.log(omittedProps); // { name: 'John' }

Utils.deepPick

deepPick()

ts
static deepPick: <T>(obj, paths) => Partial<T>;

Creates a new object by picking specified paths from the original object.

Type Parameters

T

T extends Record<string, unknown>

Parameters

obj

T

The source object.

paths

readonly string[]

An array of paths to pick from the source object.

Returns

Partial<T>

A new object containing only the picked key-value pairs.

Example

ts
const user = { id: 1, name: 'John', age: 34, childs: [ {name: 'John II', age: 10 }, { name: 'Jane II', age: 8 }, { name: 'dog', age: 2 } ]  };

const pickedDog = Utils.deepPick(user, ['id', 'age', 'childs.2']);
console.log(pickedDog); // { id: 1, age: 34, childs: [ {name: 'dog', age: 2 } ] }

const pickedProps = Utils.deepPick(user, ['id', 'age', 'childs']);
console.log(pickedProps); // { id: 1, age: 34, childs: [ {name: 'John II', age: 10 }, { name: 'Jane II', age: 8 }, { name: 'dog', age: 2 } ] }

Utils.easterDate

easterDate()

ts
static easterDate: (input?) => Date;

Returns the easter date

Parameters

input?

The date to get the easter date for.

string | number | Date

Returns

Date

The easter date.

Example

ts
const today = new Date();
const easterDate = Utils.easterDate(today);
console.log(easterDate); // <Date>

Utils.generateGuid

generateUUIDv4()

ts
static generateUUIDv4: () => string;

Generates a random UUID (universally unique identifier) according to the v4 variant (RFC 4122). The generated UUID is a string of 36 characters, with 8-4-4-4-12 hexadecimal digits separated by hyphens.

Note: This function relies on the crypto.randomUUID or crypto.getRandomValues functions to generate random numbers. If neither of these functions is available, an error is thrown.

Returns

string

A random UUID string.

Example

ts
const uuid = Utils.generateUUIDv4();
console.log(uuid); // e.g., "550e8400-e29b-41d4-a716-446655440000"

Utils.gerarCNPJ

gerarCNPJ()

ts
static gerarCNPJ: () => string;

Generates a random valid CNPJ (Brazilian National Corporate Registration Number)

Returns

string

a string containing the generated CNPJ

Example

ts
import { Utils } from '@heliomarpm/helpers';

const cnpj = Utils.gerarCNPJ();
console.log(cnpj); // e.g., "12345678000195"

Utils.gerarCPF

gerarCPF()

ts
static gerarCPF: () => string;

Generates a random valid CPF (Brazilian National Register of Individuals)

Returns

string

a string containing the generated CPF

Example

ts
import { Utils } from '@heliomarpm/helpers';

const cpf = Utils.gerarCPF();
console.log(cpf); // e.g., "12345678909"

Utils.getNestedValue

getNestedValue()

ts
static getNestedValue: <T>(obj, path) => T;

Retrieves a nested value from an object using a dot-separated path.

Type Parameters

T

T

Parameters

obj

Record<string, T>

The target object from which to retrieve the nested value.

path

string

A dot-separated string indicating the path to the nested value.

Returns

T

The nested value or undefined if the path is invalid.

Example

ts
const data = {
  user: {
    name: {
      first: "John",
      last: "Doe"
    }
  }
};
const firstName = getNestedValue(data, "user.name.first"); // "John"

Utils.groupBy

groupBy()

ts
static groupBy: <T, K>(arr, keyFn) => Record<K, T[]>;

Groups an array of objects by a specified key.

Type Parameters

T

T

The type of objects in the array.

K

K extends never

The type of the key to group by.

Parameters

arr

T[]

The array of objects to group.

keyFn

(item) => K

A function that takes an object and returns the key to group by.

Returns

Record<K, T[]>

An object where each key is a unique value of the specified key and each value is an array of objects with that key.

Example

ts
const people = [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }];
const grouped = Utils.groupBy(people, (person) => person.age);
console.log(grouped); // { 30: [{ name: 'Alice', age: 30 }], 25: [{ name: 'Bob', age: 25 }] }

Utils.ifNull

ifNull()

ts
static ifNull: <T>(value, fallback) => T;

Returns the first argument if it is not null or undefined, otherwise returns the second argument.

Type Parameters

T

T

Parameters

value

T

The value to check.

fallback

T

The value to return if value is null or undefined.

Returns

T

The first argument if it is not null or undefined, otherwise the second argument.

Example

ts
const foo = "hello";
const bar = ifNull(foo, "baz"); // "hello"

Utils.ifNullOrEmpty

ifNullOrEmpty()

ts
static ifNullOrEmpty: <T>(...values) => T;

Returns the first non-null, non-undefined, and non-empty value from the given arguments.

Type Parameters

T

T

Parameters

values

...T[]

A list of values to check.

Returns

T

The first valid value or undefined if all values are null, undefined, or empty.

Example

ts
const result = ifNullOrEmpty(null, '', undefined, 'Hello', 'World'); // "Hello"
const result2 = ifNullOrEmpty(null, '', 0); // 0
const result3 = ifNullOrEmpty([], {}); // undefined

Remarks

A value is considered "empty" if it is:

  • An empty string ('' or strings with only whitespace)
  • An empty array ([])
  • An empty object ({})

Utils.memoize

memoize()

ts
static memoize: <P, R>(fn) => MemoizedFn<P, R>;

Memoizes a function to avoid redundant computation.

Type Parameters

P

P extends unknown[]

R

R

Parameters

fn

(...args) => R

The function to memoize.

Returns

MemoizedFn<P, R>

A memoized version of the function.

Example

ts
const add = (a: number, b: number) => a + b;
const memoizedAdd = memoize(add);

const result1 = memoizedAdd(1, 2); // Calls the original function
const result2 = memoizedAdd(1, 2); // Returns cached result

Remarks

The memoized function has a clear method that can be used to clear the cache.

ts
memoizedAdd.clear(); // Clears the cache

Utils.months

months()

ts
static months: (options) => string[];

Returns an array of month names for a given locale.

Parameters

options

An object with options for formatting the month names.

locale?

LocalesArgument = "default"

The locale string to use for formatting the month names.

month?

"long" | "numeric" | "2-digit" | "short" | "narrow" = "long"

The type of month name to return. Can be 'long', 'short', or 'numeric'.

Returns

string[]

An array of month names (e.g., "January", "February", ...) for the specified locale.

Example

ts
const months = monthNames('en-US'); // ["January", "February", ..., "December"]

See

https://www.w3schools.com/jsref/jsref_tolocalestring.asp

Utils.omit

omit()

ts
static omit: <T, K>(obj, keys) => Omit<T, K>;

Creates a new object by omitting specified keys from the original object.

Type Parameters

T

T extends Record<string, unknown>

K

K extends string | number | symbol

Parameters

obj

T

The source object.

keys

readonly K[]

An array of keys to omit from the source object.

Returns

Omit<T, K>

A new object containing all key-value pairs except the omitted keys.

Example

ts
const user = { id: 1, name: 'John', age: 30, email: 'dL5mW@example.com' };

const omittedUser = Utils.omit(user, ['id', 'email']);
console.log(omittedUser); // { name: 'John', age: 30 }

Utils.once

once()

ts
static once: <P, R>(fn) => (...args) => R;

Creates a version of the given function that can only be called once. The first call to the function is executed normally, but any subsequent calls return the result of the first call.

Type Parameters

P

P extends unknown[]

R

R

Parameters

fn

(...args) => R

The function to wrap, which takes arguments of type P and returns R.

Returns

A version of the function that can only be called once, taking P and returning R.

ts
(...args): R;
Parameters
args

...P

Returns

R

Example

ts
const add = (a: number, b: number) => a + b;
const onceAdd = once(add);

const result1 = onceAdd(1, 2); // Calls the function and returns 3
const result2 = onceAdd(3, 4); // Returns 3

const init = once(() => console.log('Inicializado'));
init(); // 'Inicializado'
init(); // nada acontece

Utils.orderBy

orderBy()

ts
static orderBy: <T, K>(list, key, orderBy) => T[];

Sorts an array of objects by the specified key in ascending or descending order.

Type Parameters

T

T

The type of objects within the array.

K

K extends string | number | symbol

The key of the object by which the array should be sorted.

Parameters

list

T[]

The array of objects to be sorted.

key

K

The key of the object to sort by.

orderBy

The order of sorting, either 'asc' for ascending or 'desc' for descending. Defaults to 'asc'.

"asc" | "desc"

Returns

T[]

A new array sorted by the specified key in the specified order.

Example

ts
const people = [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }];
const sortedByName = orderBy(people, 'name'); // Sorts by name in ascending order.
const sortedByAgeDesc = orderBy(people, 'age', 'desc'); // Sorts by age in descending order.
console.log(sortedByName); // [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }]
console.log(sortedByAgeDesc); // [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }]

Utils.pick

pick()

ts
static pick: <T, K>(obj, keys) => Pick<T, K>;

Creates a new object by picking specified keys from the original object.

Type Parameters

T

T extends Record<string, unknown>

K

K extends string | number | symbol

Parameters

obj

T

The source object.

keys

readonly K[]

An array of keys to pick from the source object.

Returns

Pick<T, K>

A new object containing only the picked key-value pairs.

Example

ts
const user = { id: 1, name: 'John', age: 30, email: 'dL5mW@example.com' };
const pickedUser = Utils.pick(user, ['id', 'name']);
console.log(pickedUser); // { id: 1, name: 'John' }

Utils.pipe

pipe()

ts
static pipe: <T, R>(...fns) => (arg) => R;

Composes multiple unary functions from left to right. Ensures type safety between function outputs and inputs

Type Parameters

T

T extends unknown[]

R

R

Parameters

fns

...{ [K in string | number | symbol]: Fn<any, any> }

An array of functions to be composed.

Returns

A function that takes a single argument and processes it through the composed sequence of functions.

ts
(arg): R;
Parameters
arg

T[0]

Returns

R

Throws

Will throw an error if no functions are provided or if any argument is not a function.

Example

ts
const addOne = (x: number) => x + 1;
const numToString = (x: number) => String(x);
const length = (s: string) => s.length;

const process = Utils.pipe(addOne, numToString, length);
console.log(process(5)); // 1

Utils.randomNum

randomNum()

ts
static randomNum: (min, max) => number;

Generates a random integer between the specified minimum and maximum values, inclusive.

Parameters

min

number

The minimum value (inclusive).

max

number

The maximum value (inclusive).

Returns

number

A random integer between min and max.

Example

ts
const randomNum = Utils.randomNum(1000, 2000);
console.log(randomNum); // Outputs a random integer between 1000 and 2000

Utils.retry

retry()

ts
static retry: <T>(fn, options) => Promise<T>;

Executes a function and retries it if it fails, up to a specified number of attempts.

Type Parameters

T

T

Parameters

fn

() => Promise<T>

The function to execute and retry.

options

RetryOptions = {}

Options for retrying the function.

Returns

Promise<T>

A promise that resolves to the result of the function, or rejects with the last error.

Example

await retry(() => fetch('https://example.com/api/data'), {
  retries: 5,
  delay: 500,
  onRetry: (error, attempt) => console.log(`Attempt ${attempt} failed with error ${error.message}`)
});

Utils.setNestedValue

setNestedValue()

ts
static setNestedValue: <T>(target, path, value) => void;

Sets a nested value within an object given a path.

Type Parameters

T

T extends Record<string, unknown>

Parameters

target

T

The object to set the nested value on.

path

string

The path to the nested value. Uses dot notation.

value

unknown

The value to set the nested value to.

Returns

void

Example

ts
interface User {
  user: {
    name: {
      first: string;
      last: string;
    }
  }
}
const data: User = {
  user: {
    name: {
      first: "John",
      last: "Doe"
    }
  }
};
setNestedValue<User>(data, "user.name.first", "Jane"); // Sets data.user.name.first to "Jane"

Utils.sleep

sleep()

ts
static sleep: (ms) => Promise<void>;

Pauses execution for a specified duration.

Parameters

ms

number

The number of milliseconds to wait.

Returns

Promise<void>

A promise that resolves after the specified duration.

Example

await sleep(1000); // Pauses for 1 second

Utils.sortBy

sortBy()

ts
static sortBy(properties): (objA, objB) => number;

Returns a function that sorts an array of objects by the given properties.

If a property name starts with a '-', the sort order is reversed.

The function returned is a compare function, compliant with the API of Array.prototype.sort().

When sorting, all values are converted to strings. If a value is an object, it is converted to a string using JSON.stringify().

Parameters

properties

Properties to sort by.

string | string[]

Returns

a compare function

ts
(objA, objB): number;
Parameters
objA

Record<string, unknown>

objB

Record<string, unknown>

Returns

number

Example

ts
const validations = [
    { level: "WARNING", type: "TypeA", message: "This is a warning." },
    { level: "ERROR", type: "TypeE", message: "Something went wrong." },
    { level: "ERROR", type: "TypeE", message: "Another error." },
];

const sortedValidations = validations.sort(Utils.sortBy(['level', 'type', '-message']));
console.log(sortedValidations); // [{ level: "ERROR", type: "TypeE", message: "Something went wrong." }, ...]

Utils.throttle

throttle()

ts
static throttle: <T>(fn, wait) => (...args) => ReturnType<T>;

Creates a throttled version of the given function. Throttling is a technique for optimizing performance by limiting the number of times a function can be called within a specified time window.

Type Parameters

T

T extends (...args) => unknown

Parameters

fn

T

The function to throttle.

wait

number

The time window in milliseconds.

Returns

A throttled version of the function.

ts
(...args): ReturnType<T>;
Parameters
args

...Parameters<T>

Returns

ReturnType<T>

Example

ts
const add = (a: number, b: number) => a + b;
const throttledAdd = throttle(add, 500);

throttledAdd(1, 2); // Calls the function immediately
throttledAdd(3, 4); // Calls the function after 500ms if the previous call was outside the time window

const throttledScroll = throttle(handleScroll, 200);
window.addEventListener('scroll', throttledScroll);

Utils.weekOfYear

weekOfYear()

ts
static weekOfYear: (input?) => number;

Returns the week of the year (ISO 8601)

Parameters

input?

The date to get the week of the year for.

string | number | Date

Returns

number

The week of the year (1-53).

Example

ts
const today = new Date();
const weekOfYear = Utils.weekOfYear(today);
console.log(weekOfYear); // 1-53

Utils.weekdays

weekdays()

ts
static weekdays: (options?) => string[];

Returns an array of full weekday names for a given locale.

Parameters

options?
locale?

LocalesArgument = "default"

The locale string to use for formatting the weekday names.

weekday?

"long" | "short" | "narrow" = "long"

The type of weekday name to return. Can be 'narrow', 'short', or 'long'.

Returns

string[]

An array of full weekday names (e.g., "Sunday", "Monday", ...) for the specified locale.

Example

ts
const days = dayNames({ locale: 'en-US', weekday: 'short' });
// Output: ["Sun", "Mon", ..., "Sat"]

See

https://www.w3schools.com/jsref/jsref_tolocalestring.asp