@olan88/utilities
v1.0.1
Published
Utility functions
Readme
@olan88/utilities
A collection of typed utility functions for TypeScript projects.
Installation
npm install @olan88/utilitiesString
import { capitalize, toCamelCase, truncate, slugify, toSnakeCase, toKebabCase } from "@olan88/utilities"capitalize(str, numberOfLetters?)
Capitalizes the first numberOfLetters characters (default 1).
capitalize("hello") // "Hello"
capitalize("hello", 2) // "HEllo"toCamelCase(str, capitalize?)
Converts a string to camelCase. Pass true for PascalCase. Handles hyphens, underscores, and spaces.
toCamelCase("hello-world") // "helloWorld"
toCamelCase("hello_world") // "helloWorld"
toCamelCase("hello-world", true) // "HelloWorld"toSnakeCase(str, uppercase?)
Converts a string to snake_case. Pass true for UPPER_SNAKE_CASE.
toSnakeCase("helloWorld") // "hello_world"
toSnakeCase("helloWorld", true) // "HELLO_WORLD"toKebabCase(str)
Converts a string to kebab-case.
toKebabCase("helloWorld") // "hello-world"
toKebabCase("hello_world") // "hello-world"truncate(str, maxLength, suffix?)
Truncates a string to maxLength characters, appending a suffix (default "…").
truncate("Hello, world!", 8) // "Hello, …"
truncate("Hello, world!", 8, "...") // "Hello..."slugify(str)
Converts a string to a URL-friendly slug.
slugify("Hello World!") // "hello-world"
slugify("Foo Bar_Baz") // "foo-bar-baz"Number
import { clamp, randomInt } from "@olan88/utilities"clamp(value, min, max)
Clamps a number between min and max.
clamp(5, 1, 10) // 5
clamp(-5, 1, 10) // 1
clamp(15, 1, 10) // 10randomInt(min, max)
Returns a random integer between min and max (both inclusive).
randomInt(1, 6) // e.g. 4Array
import { chunk, unique, groupBy } from "@olan88/utilities"chunk(arr, size)
Splits an array into chunks of a given size.
chunk([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]]unique(arr)
Returns a new array with duplicate values removed.
unique([1, 1, 2, 3, 2]) // [1, 2, 3]groupBy(arr, key)
Groups an array of objects by the value of a given key.
groupBy([{ type: "a" }, { type: "b" }, { type: "a" }], "type")
// { a: [{ type: "a" }, { type: "a" }], b: [{ type: "b" }] }Object
import { pick, omit, deepClone } from "@olan88/utilities"pick(obj, keys)
Returns a new object with only the specified keys.
pick({ a: 1, b: 2, c: 3 }, ["a", "c"]) // { a: 1, c: 3 }omit(obj, keys)
Returns a new object with the specified keys removed.
omit({ a: 1, b: 2, c: 3 }, ["b"]) // { a: 1, c: 3 }deepClone(obj)
Creates a deep clone of an object.
const clone = deepClone({ a: { b: 1 } })
clone.a.b = 99 // original is unaffectedTimer
import { wait, exponentialWait } from "@olan88/utilities"wait(ms)
Waits for the specified duration.
await wait(1000) // waits 1 secondexponentialWait(attempt, delay?, backoff?)
Waits for an exponentially increasing duration. Useful for retry logic.
await exponentialWait(0) // 100ms
await exponentialWait(1) // 200ms
await exponentialWait(2) // 400ms