Skip to main content

Overview

Sorionlib provides a collection of utility functions to simplify common programming tasks. Import them from the utils module.
import { utils } from "sorionlib";

String utilities

slugify(text)

Converts a string to a URL-friendly slug.
ParameterTypeDescription
textstringThe text to convert.
Returns: string - The slugified text.
utils.slugify("Hello World!");
// "hello-world"

capitalize(text)

Capitalizes the first letter of a string.
ParameterTypeDescription
textstringThe text to capitalize.
Returns: string - The capitalized text.
utils.capitalize("hello");
// "Hello"

truncate(text, length)

Truncates a string to a specified length.
ParameterTypeDescription
textstringThe text to truncate.
lengthnumberMaximum length.
Returns: string - The truncated text with ellipsis if needed.
utils.truncate("Hello World", 5);
// "Hello..."

Array utilities

unique(array)

Removes duplicate values from an array.
ParameterTypeDescription
arrayarrayThe array to deduplicate.
Returns: array - Array with unique values.
utils.unique([1, 2, 2, 3, 3, 3]);
// [1, 2, 3]

chunk(array, size)

Splits an array into chunks of a specified size.
ParameterTypeDescription
arrayarrayThe array to split.
sizenumberSize of each chunk.
Returns: array - Array of chunks.
utils.chunk([1, 2, 3, 4, 5], 2);
// [[1, 2], [3, 4], [5]]

shuffle(array)

Randomly shuffles an array.
ParameterTypeDescription
arrayarrayThe array to shuffle.
Returns: array - The shuffled array.
utils.shuffle([1, 2, 3, 4, 5]);
// [3, 1, 5, 2, 4]

Object utilities

deepClone(object)

Creates a deep copy of an object.
ParameterTypeDescription
objectobjectThe object to clone.
Returns: object - The cloned object.
const original = { a: { b: 1 } };
const clone = utils.deepClone(original);
clone.a.b = 2;
console.log(original.a.b); // 1

merge(target, source)

Deep merges two objects.
ParameterTypeDescription
targetobjectThe target object.
sourceobjectThe source object.
Returns: object - The merged object.
utils.merge({ a: 1 }, { b: 2 });
// { a: 1, b: 2 }

Date utilities

formatDate(date, format)

Formats a date according to a pattern.
ParameterTypeDescription
dateDateThe date to format.
formatstringFormat pattern.
Returns: string - The formatted date.
utils.formatDate(new Date(), "YYYY-MM-DD");
// "2024-01-15"

timeAgo(date)

Returns a human-readable relative time string.
ParameterTypeDescription
dateDateThe date to compare.
Returns: string - Relative time string.
utils.timeAgo(new Date(Date.now() - 60000));
// "1 minute ago"