JavaScript utilities Free template
JavaScript utility belt
Eight small, dependency-free helper functions (debounce, throttle, formatting, deep clone, grouping and more) with a live demo.
The preview runs in a sandbox: it cannot reach your account, cookies or the network.
About this template
A file of everyday JavaScript helpers that you can copy into any project: debounce, throttle, formatCurrency, formatRelativeTime, deepClone, groupBy, chunk and slugify. Each one is short, documented with a comment and has no dependencies. The demo page runs them and prints the results, and the Console tab of the playground shows the same output, so you can see how each function behaves.
Look under the hood
Included source files
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>JavaScript utilities</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 46rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
.line { display: flex; flex-direction: column; padding: 0.5rem 0; border-bottom: 1px solid #e3e6e9; }
code { color: #c00000; }
</style>
</head>
<body>
<h1>JavaScript utilities</h1>
<p>Results of each helper in <code>utils.js</code>. Open the Console tab to see the same output.</p>
<div id="output"></div>
<script src="utils.js"></script>
<script src="demo.js"></script>
</body>
</html>
// Runs each helper and shows the result on the page and in the console.
const output = document.getElementById('output');
function show(label, value) {
const text = typeof value === 'string' ? value : JSON.stringify(value);
console.log(label, '->', text);
const line = document.createElement('div');
line.className = 'line';
const name = document.createElement('code');
name.textContent = label;
const result = document.createElement('span');
result.textContent = text;
line.append(name, result);
output.append(line);
}
show("formatCurrency(1234.5, 'EUR', 'de-DE')", formatCurrency(1234.5, 'EUR', 'de-DE'));
show("formatCurrency(99.99)", formatCurrency(99.99));
show('formatRelativeTime(1 hour ago)', formatRelativeTime(new Date(Date.now() - 3600 * 1000)));
show('formatRelativeTime(in 3 days)', formatRelativeTime(new Date(Date.now() + 3 * 86400 * 1000)));
show("slugify('Hello, World! Ça va?')", slugify('Hello, World! Ça va?'));
show('chunk([1,2,3,4,5], 2)', chunk([1, 2, 3, 4, 5], 2));
show("groupBy by first letter", groupBy(['apple', 'avocado', 'banana', 'blueberry', 'cherry'], (word) => word[0]));
const original = { name: 'Ada', tags: ['math'], born: new Date('1815-12-10') };
const copy = deepClone(original);
copy.tags.push('code');
show('deepClone keeps the original unchanged', { original: original.tags, copy: copy.tags });
// debounce: five quick calls run once, 200 ms after the last one.
let debounced = 0;
const onType = debounce(() => { debounced++; show('debounce ran', 'once after 5 calls (count: ' + debounced + ')'); }, 200);
for (let i = 0; i < 5; i++) onType();
// throttle: only the first call in each 300 ms window runs.
let throttled = 0;
const onScroll = throttle(() => { throttled++; }, 300);
for (let i = 0; i < 5; i++) onScroll();
show('throttle ran', throttled + ' time(s) for 5 immediate calls');
/**
* Everyday helpers with no dependencies. Copy the ones you need.
*/
/** Runs `fn` only after `wait` ms have passed without another call (search boxes, resize handlers). */
function debounce(fn, wait = 250) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
/** Runs `fn` at most once every `wait` ms (scroll handlers). */
function throttle(fn, wait = 250) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
return fn.apply(this, args);
}
};
}
/** formatCurrency(1234.5, 'EUR', 'de-DE') -> "1.234,50 €" */
function formatCurrency(amount, currency = 'USD', locale = 'en-US') {
return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(amount);
}
/** formatRelativeTime(new Date(Date.now() - 3600000)) -> "1 hour ago" */
function formatRelativeTime(date, locale = 'en') {
const seconds = Math.round((new Date(date).getTime() - Date.now()) / 1000);
const units = [['year', 31536000], ['month', 2592000], ['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]];
const formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
for (const [unit, size] of units) {
if (Math.abs(seconds) >= size || unit === 'second') {
return formatter.format(Math.round(seconds / size), unit);
}
}
}
/** A real copy of plain data (objects, arrays, dates). Functions are not copied. */
function deepClone(value) {
return structuredClone(value);
}
/** groupBy([{t:'a'},{t:'b'},{t:'a'}], (x) => x.t) -> { a: [..], b: [..] } */
function groupBy(items, getKey) {
return items.reduce((groups, item) => {
const key = getKey(item);
(groups[key] ||= []).push(item);
return groups;
}, {});
}
/** chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]] */
function chunk(items, size) {
const result = [];
for (let i = 0; i < items.length; i += size) result.push(items.slice(i, i + size));
return result;
}
/** slugify('Hello, World! Ça va?') -> "hello-world-ca-va" */
function slugify(text) {
return text
.normalize('NFKD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
Update history
- 1.0.0
First release.