215+
Functions
0
Dependencies
12
Categories
30KB
Minified
MIT
License
โถ Live Demo
โ result will appear here
๐ Usage
ESM (recommended)
import { slugify, chunk, debounce, uuid } from 'utilitx'; slugify('Hello World!') // "hello-world" chunk([1,2,3,4,5], 2) // [[1,2],[3,4],[5]] uuid() // "a1b2c3d4-..."
CommonJS
const { slugify, isEmail, debounce } = require('utilitx');
CDN โ browser <script> tag (no install)
<script src="https://unpkg.com/utilitx/utilitx.min.js"></script> <script> utilitx.slugify("Hello World") // "hello-world" utilitx.uuid() // "a1b2-..." utilitx.formatCurrency(1234) // "$1,234.00" </script>
๐ String
slugify(str)
URL-safe slug
"Hello World!" โ "hello-world"
truncate(str, len)
Truncate with ellipsis
"Hello World", 5 โ "Hello..."
capitalize(str)
Capitalize first letter
"hello" โ "Hello"
titleCase(str)
Every word capitalized
"hello world" โ "Hello World"
camelCase(str)
Convert to camelCase
"hello-world" โ "helloWorld"
snakeCase(str)
Convert to snake_case
"helloWorld" โ "hello_world"
kebabCase(str)
Convert to kebab-case
"helloWorld" โ "hello-world"
escapeHtml(str)
Escape HTML / prevent XSS
"" โ "<b>"
reverseStr(str)
Reverse a string
"hello" โ "olleh"
isPalindrome(str)
Check palindrome
"racecar" โ true
randomString(len?)
Random alphanumeric string
8 โ "aB3kX9mZ"
stripHtml(str)
Remove HTML tags
"hi" โ "hi"
initials(str)
Get name initials
"John Doe" โ "JD"
template(str, data)
Simple string template
"Hi {{name}}", {name:"Dev"}
wordCount(str)
Count words
"hello world" โ 2
fuzzySearch(list, q)
Fuzzy search array
fuzzySearch([...], "ap")
highlight(str, q)
Highlight matches
wraps matches in
contains(str, sub)
Case-insensitive check
contains("Hello","hello",true)
parseCSVRow(row)
Parse CSV row string
โ string[]
toCSV(arr)
Array of objects to CSV
โ CSV string
๐ Array
chunk(arr, size)
Split into chunks
[1,2,3,4,5],2 โ [[1,2],[3,4],[5]]
unique(arr)
Remove duplicates
[1,2,2,3] โ [1,2,3]
flatten(arr)
Deep flatten
[1,[2,[3]]] โ [1,2,3]
shuffle(arr)
Random shuffle
[1,2,3] โ [3,1,2]
sample(arr)
One random element
[1,2,3] โ 2
sampleSize(arr, n)
n random elements
[1,2,3,4],2 โ [3,1]
groupBy(arr, key)
Group by key/fn
groupBy(users,"role")
sortBy(arr, key)
Sort by key asc/desc
sortBy(items,"price","asc")
intersection(a,b)
Elements in both
[1,2,3],[2,3] โ [2,3]
difference(a,b)
In a but not b
[1,2,3],[2] โ [1,3]
zip(...arrays)
Zip into tuples
[1,2],["a","b"] โ [[1,"a"],[2,"b"]]
sum / average / min / max
Math on arrays
sum([1,2,3]) โ 6
range(start, end, step?)
Create number range
range(1,5) โ [1,2,3,4,5]
partition(arr, fn)
Split by predicate
โ [passing[], failing[]]
compact(arr)
Remove falsy values
[0,1,false,2] โ [1,2]
take / drop / nth
Slice helpers
take([1,2,3],2) โ [1,2]
frequencies(arr)
Count occurrences
["a","b","a"] โ {a:2,b:1}
paginate(arr, page, size)
Paginate array
โ {data,page,total,...}
insertAt / removeAt
Insert or remove by index
insertAt([1,3],1,2) โ [1,2,3]
rotate(arr, n)
Rotate elements
rotate([1,2,3],1) โ [2,3,1]
๐๏ธ Object
deepClone(obj)
Deep clone
const b = deepClone(a)
deepMerge(a,b)
Recursive merge
deepMerge({a:1},{b:2})
pick(obj, keys)
Extract keys
pick(user,["id","name"])
omit(obj, keys)
Remove keys
omit(user,["password"])
get(obj, path)
Safe nested get
get(obj,"a.b.c",null)
set(obj, path, val)
Safe nested set
set(obj,"a.b",99)
flattenObj(obj)
Flatten to dot-path
{a:{b:1}} โ {"a.b":1}
diff(a, b)
Shallow object diff
โ {key:{from,to}}
keyBy(arr, key)
Array โ keyed map
keyBy(users,"id")
mapValues(obj,fn)
Map object values
mapValues({a:1},x=>x*2)
filterObj(obj,fn)
Filter object entries
filterObj(obj,v=>v>0)
renameKeys(obj,map)
Rename object keys
renameKeys(o,{old:"new"})
invertObj(obj)
Swap keys & values
{a:"x"} โ {x:"a"}
has(obj, path)
Check nested key exists
has(obj,"a.b.c")
deepEqual(a,b)
Deep equality check
deepEqual({a:1},{a:1}) โ true
๐ข Number
clamp(n,min,max)
Keep n in bounds
clamp(150,0,100) โ 100
randomInt(min,max)
Random integer
randomInt(1,6) โ 4
formatBytes(bytes)
Human file size
1048576 โ "1 MB"
round(n,decimals?)
Round to places
round(3.14159,2) โ 3.14
inRange(n,min,max)
Is n in range?
inRange(5,1,10) โ true
formatNumber(n)
Thousand separators
1000000 โ "1,000,000"
percentage(val,total)
Calculate %
percentage(25,200) โ 12.5
uuid()
Generate UUID v4
โ "a1b2c3d4-..."
lerp(a,b,t)
Linear interpolation
lerp(0,100,0.5) โ 50
mapRange(n,...)
Map between ranges
mapRange(5,0,10,0,100)โ50
isPrime(n)
Check prime number
isPrime(7) โ true
factorial(n)
Factorial
factorial(5) โ 120
gcd / lcm
Math helpers
gcd(12,8) โ 4
median / mode / stdDev
Statistics
median([1,2,3,4,5]) โ 3
๐ Date
timeAgo(date)
Relative time string
โ "3 minutes ago"
formatDate(date,fmt?)
Format with tokens
formatDate(d,"DD/MM/YYYY")
daysBetween(a,b)
Days between dates
โ 10
addDays(date,n)
Add days
addDays(today,7)
isWeekend(date)
Saturday or Sunday?
โ true / false
startOfDay / endOfDay
Day boundaries
โ 00:00:00 / 23:59:59
isSameDay(a,b)
Same calendar day?
โ true / false
โ Validate
isEmail(str)
Valid email
user@example.com โ true
isURL(str)
Valid URL
https://x.com โ true
isEmpty(val)
Null/empty check
"" / [] / {} โ true
isStrongPassword(str)
8+ chars, upper/lower/digit/symbol
โ true/false
passwordStrength(str)
Strength 0โ4
"Abc@1234" โ 4
isCreditCard(str)
Luhn check
โ true / false
isIPv4(str)
Valid IPv4
192.168.1.1 โ true
isHexColor(str)
Valid hex color
#ff6600 โ true
isUUID(str)
Valid UUID v4
โ true / false
isAlpha / isAlphanumeric
Character checks
โ true / false
โก Async
sleep(ms)
Promise delay
await sleep(1000)
retry(fn,n?,delay?)
Retry on failure
retry(()=>fetch(url),3,500)
debounce(fn,ms)
Fire after inactivity
debounce(search,300)
throttle(fn,ms)
Max once per interval
throttle(onScroll,100)
tryCatch(promise)
[err,result] tuple
const [e,d]=await tryCatch(fetch(...))
series(fns)
Run in sequence
await series([fn1,fn2,fn3])
pLimit(fns,limit?)
Parallel + concurrency
pLimit(fns,3)
withTimeout(p,ms)
Reject after timeout
withTimeout(fetch(url),5000)
poll(fn,opts)
Poll until truthy
await poll(()=>isReady())
deferred()
External resolve/reject
const {promise,resolve}=deferred()
timeIt(fn)
Time async function
โ {result,ms:42}
๐จ Color
hexToRgb(hex)
Hex โ {r,g,b}
"#ff6600" โ {r:255,g:102,b:0}
rgbToHex(r,g,b)
RGB โ hex string
255,102,0 โ "#ff6600"
randomColor()
Random hex color
โ "#a3f4b2"
lighten(hex,amount)
Lighten by %
lighten("#333",20)
darken(hex,amount)
Darken by %
darken("#ff6600",30)
๐ง Functions
memoize(fn)
Cache results
const fast=memoize(slowFn)
once(fn)
Call only once
const init=once(setup)
compose(...fns)
Right-to-left pipe
compose(f,g)(x) โ f(g(x))
pipe(...fns)
Left-to-right pipe
pipe(f,g)(x) โ g(f(x))
curry(fn)
Curried function
curry(add)(1)(2) โ 3
negate(fn)
Negate predicate
negate(isEmail)("bad") โ true
benchmark(fn,n?)
Measure avg time
โ avg ms over n iterations
๐๏ธ Data Structures
createStack()
Stack: push/pop/peek
.push(1,2,3) .pop() โ 3
createQueue()
Queue: enqueue/dequeue
.enqueue(1) .dequeue() โ 1
createEmitter()
Event emitter
.on("x",fn) .emit("x")
createStore(init)
Reactive state store
.set({count:1}) .subscribe(fn)
createLRU(capacity)
LRU Cache
createLRU(100).set("k","v")
โจ Format
formatCurrency(n,currency?)
Currency format
1234.56 โ "$1,234.56"
formatPhone(str)
Phone formatting
"1234567890" โ "(123) 456-7890"
maskString(str,char?,n?)
Mask sensitive data
"4111..." โ "****1111"
ordinal(n)
Add ordinal suffix
1โ"1st" 2โ"2nd" 21โ"21st"
pluralize(n,word)
Pluralize word
pluralize(2,"cat") โ "cats"
compactNumber(n)
Compact notation
1500000 โ "1.5M"
toBase64 / fromBase64
Encode/decode base64
โ string
hashCode(str)
Fast non-crypto hash
"hello" โ "3610a686"
safeJsonParse(str)
Parse without throwing
โ value or null
encodeParam / decodeParam
URL encode/decode
โ string
๐ DOM (browser)
copyToClipboard(str)
Copy to clipboard
await copyToClipboard("hi")
scrollTo(el)
Smooth scroll
scrollTo(document.querySelector("#x"))
onClickOutside(el,fn)
Outside click listener
const off=onClickOutside(modal,close)
parseQueryString(url?)
Query โ object
"?a=1&b=2" โ {a:"1",b:"2"}
buildQueryString(params)
Object โ query string
{a:1} โ "?a=1"
loadScript(src)
Load external script
await loadScript("https://...")
lsSet/lsGet/lsRemove
localStorage with TTL
lsSet("key",val,3600000)
isBrowser / isNode
Environment detection
โ true / false
prefersDark()
Dark mode check
โ true / false