Library · printable
The one-line sheet.
Every curated utility, as the code itself. 323 entries, grouped by topic — read it in a minute, print it for the wall, follow a link for the edge cases.
Array 50 lines
- Clone an array
function clone(values) { return [...values]; } - Remove duplicate values
function unique(values) { return [...new Set(values)]; } - Flatten a nested array
function flatten(values) { return values.flat(Infinity); } - Split an array into chunks
function chunk({ values, size }) { return Array.from({ length: Math.ceil(values.length / size) }, (_, i) => values.slice(i * size, (i + 1) * size)); } - Find the intersection of arrays
function intersection({ left, right }) { const other = new Set(right); return [...new Set(left)].filter(value => other.has(value)); } - Sort numbers in ascending order
function sortNumbers(values) { return [...values].sort((a, b) => a - b); } - Sum an array of numbers
function sum(values) { return values.reduce((total, value) => total + value, 0); } - Group objects by a key
function groupBy({ values, key }) { const groups = new Map(); for (const value of values) { const group = String(value[key]); groups.set(group, [...(groups.get(group) || []), value]); } return Object.fromEntries(groups); } - Cast a value as an array
function castArray(value) { return Array.isArray(value) ? value : [value]; } - Convert an array of strings to numbers
function toNumbers(values) { return values.map(Number); } - Get all subsets of an array
function getSubsets(values) { return values.reduce((subsets, value) => subsets.concat(subsets.map(subset => [...subset, value])), [[]]); } - Get union of arrays
function union(arrays) { return [...new Set(arrays.flat())]; } - Swap the rows and columns of a matrix
function transpose(matrix) { return matrix[0].map((_, column) => matrix.map(row => row[column])); } - Swap two array items
function swapItems({ values, i, j }) { const copy = [...values]; [copy[i], copy[j]] = [copy[j], copy[i]]; return copy; } - Unzip an array of arrays
function unzip(arrays) { return Array.from({ length: Math.max(0, ...arrays.map(array => array.length)) }, (_, i) => arrays.filter(array => i < array.length).map(array => array[i])); } - Compare two arrays
function isEqual({ a, b }) { return a.length === b.length && a.every((value, i) => Object.is(value, b[i])); } - Convert an array of objects to a single object
function toObject({ values, key }) { return Object.fromEntries(values.map(item => [item[key], item])); } - Count the occurrences of a value in an array
function countOccurrences({ values, value }) { return values.filter(item => item === value).length; } - Count the occurrences of array elements
function countEach(values) { return { ...values.reduce((counts, value) => ((counts[value] = (counts[value] || 0) + 1), counts), Object.create(null)) }; } - Create an array of numbers in the given range
function range({ min, max }) { return Array.from({ length: max - min + 1 }, (_, i) => min + i); } - Create cartesian product
function cartesian(sets) { return sets.reduce((product, set) => product.flatMap(prefix => set.map(item => [...prefix, item])), [[]]); } - Find the minimum item of an array
function min(values) { return Math.min(...values); } - Get the rank of an array of numbers
function ranking(values) { return values.map(value => values.filter(other => other > value).length + 1); } - Remove falsy values from array
function removeFalsy(values) { return values.filter(Boolean); } - Zip multiple arrays
function zip(arrays) { return Array.from({ length: Math.max(0, ...arrays.map(array => array.length)) }, (_, i) => arrays.map(array => array[i] ?? null)); } - Compare two arrays regardless of order
function isEqualIgnoringOrder({ a, b }) { const normalize = values => JSON.stringify([...new Set(values)].sort()); return normalize(a) === normalize(b); } - Count by the properties of an array of objects
function countBy({ values, key }) { return { ...values.reduce((counts, item) => ((counts[item[key]] = (counts[item[key]] || 0) + 1), counts), Object.create(null)) }; } - Create an array of cumulative sum
function accumulate(values) { let total = 0; return values.map(value => (total += value)); } - Find the index of the maximum item of an array
function indexOfMax(values) { return values.reduce((best, value, i) => (value > values[best] ? i : best), 0); } - Find the maximum item of an array by given key
function maxBy({ values, key }) { return values.reduce((best, item) => (best === null || item[key] > best[key] ? item : best), null); } - Find the maximum item of an array
function max(values) { return Math.max(...values); } - Generate an array of alphabet characters
function alphabet(count) { return Array.from({ length: count }, (_, i) => String.fromCharCode(97 + i)); } - Get all arrays of consecutive elements
function windows({ values, size }) { return size > values.length ? [] : values.slice(size - 1).map((_, i) => values.slice(i, i + size)); } - Get indices of a value in an array
function indices({ values, value }) { return values.flatMap((item, i) => (item === value ? [i] : [])); } - Get the average of an array
function average(values) { return values.reduce((sum, value) => sum + value, 0) / values.length; } - Get the unique values of an array
function uniqueValues(values) { return [...new Set(values)]; } - Intersperse element between elements
function intersperse({ values, separator }) { return values.flatMap((value, i) => (i === 0 ? [value] : [separator, value])); } - Sort an array of items by given key
function sortBy({ values, key }) { return [...values].sort((a, b) => (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0)); } - Check if an array is empty
function isEmptyArray(value) { return Array.isArray(value) && !value.length; } - Find the closest number from an array
function closest({ values, target }) { return values.reduce((best, value) => (Math.abs(value - target) < Math.abs(best - target) ? value : best)); } - Find the index of the minimum item of an array
function indexOfMin(values) { return values.reduce((best, value, i) => (value < values[best] ? i : best), 0); } - Find the length of the longest string in an array
function longestLength(words) { return Math.max(0, ...words.map(word => word.length)); } - Find the minimum item of an array by given key
function minBy({ values, key }) { return values.reduce((best, item) => (best === null || item[key] < best[key] ? item : best), null); } - Get all nth items of an array
function getNthItems({ values, nth }) { return values.filter((_, i) => i % nth === nth - 1); } - Merge two arrays
function merge({ a, b, unique = false }) { return unique ? [...new Set([...a, ...b])] : [...a, ...b]; } - Repeat an array
function repeatArray({ values, times }) { return Array(times).fill(values).flat(); } - Empty an array
function empty(values) { values.length = 0; return values; } - Find the index of the last matching item of an array
function lastIndex(values, predicate) { return values.findLastIndex(predicate); } - Partition an array based on a condition
function partition(values, predicate) { return values.reduce((groups, value) => (groups[predicate(value) ? 0 : 1].push(value), groups), [[], []]); } - Shuffle an array
function shuffle(values) { const result = [...values]; for (let i = result.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [result[i], result[j]] = [result[j], result[i]]; } return result; }
Object 13 lines
- Pick properties from an object
function pick({ value, keys }) { return Object.fromEntries(keys.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]])); } - Omit properties from an object
function omit({ value, keys }) { return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key))); } - Create an object from pairs of key and value
function toObject(pairs) { return Object.fromEntries(pairs); } - Check if multiple objects are equal
function areEqual(objects) { return objects.every(object => JSON.stringify(object) === JSON.stringify(objects[0])); } - Get the value at given path of an object
function getValue({ path, object }) { return path.split('.').reduce((value, key) => (value == null ? undefined : value[key]), object) ?? null; } - Immutably rename object keys
function renameKeys({ keysMap, object }) { return Object.fromEntries(Object.entries(object).map(([key, value]) => [keysMap[key] || key, value])); } - Invert keys and values of an object
function invert(object) { return Object.fromEntries(Object.entries(object).map(([key, value]) => [value, key])); } - Extract values of a property from an array of objects
function pluck({ objects, property }) { return objects.map(object => object[property] ?? null); } - Sort an object by its properties
function sortKeys(object) { return Object.fromEntries(Object.keys(object).sort().map(key => [key, object[key]])); } - Remove all null and undefined properties from an object
function removeNullish(object) { return Object.fromEntries(Object.entries(object).filter(([, value]) => value != null)); } - Shallow copy an object
function shallowCopy(object) { return { ...object }; } - Get unique objects from an array by key
function uniqueBy({ objects, key }) { return [...new Map(objects.map(item => [item[key], item])).values()]; } - Create an empty map that does not have properties
function createDictionary() { return Object.create(null); }
String 51 lines
- Capitalize a string
function capitalize(value) { const [first, ...rest] = Array.from(value); return first ? first.toUpperCase() + rest.join('') : ''; } - Reverse a string
function reverse(value) { return Array.from(value).reverse().join(''); } - Check a palindrome
function palindrome(value) { return value === Array.from(value).reverse().join(''); } - Create a simple URL slug
function slugify(value) { return value.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); } - Convert snake case to camel case
function camelCase(value) { return value.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()); } - Remove duplicate lines
function uniqueLines(value) { return [...new Set(value.split(/\r?\n/))].join('\n'); } - Check if a URL is absolute
function isAbsoluteUrl(url) { return /^[a-z][a-z0-9+.-]*:/i.test(url); } - Check if a path is relative
function isRelative(path) { return !/^([a-z]+:)?[\\/]/i.test(path); } - Convert a base64 encoded string to an Uint8Array
function base64ToBytes(base64) { return Array.from(atob(base64), char => char.charCodeAt(0)); } - Convert an Uint8Array to a base64 encoded string
function bytesToBase64(bytes) { return btoa(String.fromCharCode(...bytes)); } - Check if a string consists of a repeated character sequence
function consistsRepeatedSubstring(text) { return `${text}${text}`.indexOf(text, 1) !== text.length; } - Check if two strings are anagrams
function areAnagram({ first, second }) { const sorted = text => Array.from(text.toLowerCase()).sort().join(''); return sorted(first) === sorted(second); } - Convert a letter to its regional indicator emoji
function letterToEmoji(letter) { return String.fromCodePoint(letter.toLowerCase().charCodeAt(0) + 127365); } - Sort the characters of a string in alphabetical order
function sortCharacters(text) { return Array.from(text).sort((a, b) => a.localeCompare(b, 'en')).join(''); } - Generate a hash of a string
function hashString(text) { return text.split('').reduce((hash, char) => (Math.imul(31, hash) + char.charCodeAt(0)) | 0, 0); } - Get the length of a string in bytes
function byteLength(text) { return new TextEncoder().encode(text).length; } - Strip ANSI codes from a string
function stripAnsi(text) { return text.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, ''); } - Swap case of characters in a string
function swapCase(text) { return Array.from(text).map(char => char === char.toLowerCase() ? char.toUpperCase() : char.toLowerCase()).join(''); } - Convert a string to Pascal case
function toPascalCase(text) { return (text.match(/[a-zA-Z0-9]+/g) || []).map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(''); } - Convert a Windows file path to a Unix path
function toUnixPath(path) { return path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, ''); } - Convert camel case to kebab case and vice versa
function convertCase({ value, to }) { return to === 'kebab' ? value.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase() : value.replace(/-./g, match => match[1].toUpperCase()); } - Count the number of words in a string
function countWords(text) { return (text.match(/\S+/g) || []).length; } - Get the file extension from a file name
function fileExtension(name) { const dot = name.lastIndexOf('.'); return dot > 0 ? name.slice(dot + 1) : ''; } - Get the file name from a URL
function fileNameFromUrl(url) { const path = url.split(/[?#]/)[0]; return path.slice(path.lastIndexOf('/') + 1); } - Get the number of a character in a string
function characterCount({ text, char }) { return text.split(char).length - 1; } - Normalize file path slashes
function normalizePath(path) { return path.replace(/[\\/]+/g, '/'); } - Remove spaces from a string
function removeSpaces(text) { return text.replace(/\s/g, ''); } - Repeat a string
function repeat({ text, times }) { return text.repeat(times); } - Replace all line breaks with br elements
function nl2br(text) { return text.replace(/\r?\n/g, '<br>'); } - Replace all tab characters with spaces
function tabsToSpaces({ text, spaces }) { return text.replaceAll('\t', ' '.repeat(spaces)); } - Mask the first characters of a string
function maskStart({ text, count, mask }) { return text.slice(count).padStart(text.length, mask); } - Reverse the order of lines of a text
function reverseLines(text) { return text.split(/\r?\n/).reverse().join('\n'); } - Sort lines of a text document in alphabetical order
function sortLines(text) { return text.split(/\r?\n/).sort().join('\n'); } - Trim slashes at the beginning and the end of a string
function trimSlashes(text) { return text.replace(/^\/+|\/+$/g, ''); } - Trim the file extension from a file name
function trimExtension(name) { const dot = name.lastIndexOf('.'); return dot > 0 ? name.slice(0, dot) : name; } - Convert a string to camel case
function toCamelCase(text) { return text.trim().replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : ''); } - Convert the name of an Excel column to a number
function columnNumber(column) { return column.split('').reduce((total, letter) => total * 26 + parseInt(letter, 36) - 9, 0); } - Count the occurrences of a character in a string
function countOccurrences({ text, char }) { return Array.from(text).filter(item => item === char).length; } - Decapitalize a string
function decapitalize(text) { const [first = '', ...rest] = Array.from(text); return first.toLowerCase() + rest.join(''); } - Escape HTML special characters
function escapeHtml(text) { return text.replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]); } - Format a string
function format({ template, values }) { return values.reduce((text, value, i) => text.replaceAll(`{${i}}`, String(value)), template); } - Get the base URL without any parameters
function baseUrl(url) { return url.split(/[?#]/)[0]; } - Make the first character of a string lowercase
function lowercaseFirst(text) { return `${text.charAt(0).toLowerCase()}${text.slice(1)}`; } - Prepend a line number to each line of a text document
function prependNumbers(text) { return text.split(/\r?\n/).map((line, i) => `${String(i + 1).padStart(2, ' ')} ${line}`).join('\n'); } - Replace multiple spaces with a single space
function collapseSpaces(text) { return text.replace(/\s\s+/g, ' '); } - Trim a character from both ends
function trimCharacter({ text, char }) { const escaped = char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return text.replace(new RegExp(`^(?:${escaped})+|(?:${escaped})+$`, 'g'), ''); } - Truncate a string at full words
function truncateWords({ text, max, suffix }) { if (text.length <= max) return text; const cut = text.slice(0, max - suffix.length); const space = cut.lastIndexOf(' '); return `${space > 0 ? cut.slice(0, space) : cut}${suffix}`; } - Unescape HTML special characters
function unescapeHtml(text) { return text.replace(/&(?:amp|lt|gt|quot|#0*39);/g, entity => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[entity] ?? "'"); } - Uppercase the first character of each word
function uppercaseWords(text) { return text.split(' ').map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(' '); } - Remove empty lines of a text document
function removeEmptyLines(text) { return text.split(/\r?\n/).filter(line => line.trim() !== '').join('\n'); } - Decode numeric HTML entities
function decodeNumericEntities(text) { return text.replace(/&#(x[0-9a-f]+|\d+);/gi, (entity, code) => { const point = code[0].toLowerCase() === 'x' ? parseInt(code.slice(1), 16) : Number(code); return point <= 0x10ffff ? String.fromCodePoint(point) : entity; }); }
Number 22 lines
- Clamp a number to a range
function clamp({ value, min, max }) { return Math.min(max, Math.max(min, value)); } - Round to a number of digits
function roundTo({ value, digits }) { const factor = 10 ** digits; return Math.round(value * factor) / factor; } - Add an ordinal suffix to a number
function addOrdinal(n) { return `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`; } - Calculate Fibonacci numbers
function fibonacci(n, memo = {}) { return memo[n] || (n <= 2 ? 1 : (memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo))); } - Calculate the division of numbers
function division(values) { return values.reduce((a, b) => a / b); } - Calculate the mod of a collection index
function mod({ index, length }) { return ((index % length) + length) % length; } - Compute the greatest common divisor between two numbers
function gcd({ a, b }) { return b === 0 ? Math.abs(a) : gcd({ a: b, b: a % b }); } - Calculate the average of numbers
function averageOf(values) { return values.reduce((a, b) => a + b) / values.length; } - Calculate the remainder of division of numbers
function remainder(values) { return values.reduce((a, b) => a % b); } - Subtract numbers
function subtract(values) { return values.reduce((a, b) => a - b); } - Calculate the factorial of a number
function factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); } - Calculate the sum of numbers
function sumOf(values) { return values.reduce((a, b) => a + b); } - Convert a number to equivalent characters
function toChars(n) { return `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`; } - Multiply numbers
function multiply(values) { return values.reduce((a, b) => a * b); } - Truncate a number at decimal
function truncate(n) { return Math.trunc(n); } - Convert a string to a number
function toNumber(text) { return +text; } - Convert decimal to binary recursively
function decToBinary(num) { return num === 0 ? 0 : (num % 2) + 10 * decToBinary(Math.floor(num / 2)); } - Prefix an integer with zeros
function prefixWithZeros({ n, length }) { return String(n).padStart(length, '0'); } - Truncate a number to decimal places without rounding
function toFixedDown({ n, digits }) { return Number(`${n}`.match(new RegExp(`^-?\\d+(?:\\.\\d{0,${digits}})?`))[0]); } - Wrap a number between two values
function wrap({ num, min, max }) { return ((((num - min) % (max - min)) + (max - min)) % (max - min)) + min; } - Get the arrays of digits from a number
function digitize(n) { return [...`${n}`].map(digit => Number(digit)); } - Get the intersection range between two ranges
function intersectRanges({ a, b }) { return a[0] > b[1] || a[1] < b[0] ? [] : [Math.max(a[0], b[0]), Math.min(a[1], b[1])]; }
Date & time 24 lines
- Compare two dates
function compareDates({ first, second }) { return Math.sign(new Date(first).getTime() - new Date(second).getTime()); } - Add AM PM suffix to an hour
function suffixAmPm(hour) { return `${hour % 12 === 0 ? 12 : hour % 12}${hour < 12 ? 'am' : 'pm'}`; } - Calculate the number of days between two dates
function diffDays({ first, second }) { return Math.round(Math.abs(Date.parse(second) - Date.parse(first)) / 86400000); } - Convert a date to YYYY-MM-DD format
function formatYmd(dateTime) { return new Date(dateTime).toISOString().slice(0, 10); } - Convert seconds to hh:mm:ss format
function formatSeconds(seconds) { return [Math.floor(seconds / 3600), Math.floor(seconds % 3600 / 60), seconds % 60].map(part => String(part).padStart(2, '0')).join(':'); } - Calculate the number of months between two dates
function monthDiff({ start, end }) { const a = new Date(start), b = new Date(end); return Math.max(0, (b.getUTCFullYear() - a.getUTCFullYear()) * 12 - a.getUTCMonth() + b.getUTCMonth()); } - Extract year, month, day, hour, minute, second and millisecond from a date
function extract(dateTime) { return new Date(dateTime).toISOString().split(/[^0-9]/).slice(0, -1); } - Get the current timestamp in seconds
function unixSeconds(now) { return Math.floor(Date.parse(now) / 1000); } - Get the first date in the month of a date
function firstDateOfMonth(date) { const d = new Date(date); d.setUTCDate(1); return d.toISOString().slice(0, 10); } - Get the total number of days in a year
function daysInYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365; } - Set the time of a date to midnight
function midnightUtc(now) { const d = new Date(now); d.setUTCHours(0, 0, 0, 0); return d.toISOString(); } - Format a date for the given locale
function formatDate({ date, locale }) { return new Intl.DateTimeFormat(locale, { timeZone: 'UTC' }).format(new Date(date)); } - Get the current quarter of a date
function quarter(date) { return Math.ceil((new Date(date).getUTCMonth() + 1) / 3); } - Get the day of the year from a date
function dayOfYear(date) { return Math.round((Date.parse(date) - Date.parse(`${date.slice(0, 4)}-01-01`)) / 86400000) + 1; } - Get the last date in the month of a date
function lastDateOfMonth(date) { const d = new Date(date); d.setUTCMonth(d.getUTCMonth() + 1, 0); return d.toISOString().slice(0, 10); } - Get the month name of a date
function monthName(date) { return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][new Date(date).getUTCMonth()]; } - Get the tomorrow date
function tomorrow(date) { const d = new Date(date); d.setUTCDate(d.getUTCDate() + 1); return d.toISOString().slice(0, 10); } - Get the weekday of a date
function weekday(date) { return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][new Date(date).getUTCDay()]; } - Sort an array of dates
function sortDates({ dates, order = 'asc' }) { const sorted = [...dates].sort((a, b) => Date.parse(a) - Date.parse(b)); return order === 'desc' ? sorted.reverse() : sorted; } - Determine one year from a date
function plusOneYear(date) { const d = new Date(date); d.setUTCFullYear(d.getUTCFullYear() + 1); return d.toISOString().slice(0, 10); } - Get the number of days in a given month
function daysInMonth({ year, month }) { const d = new Date(0); d.setUTCFullYear(year, month, 0); return d.getUTCDate(); } - Get the yesterday date
function yesterday(date) { const d = new Date(date); d.setUTCDate(d.getUTCDate() - 1); return d.toISOString().slice(0, 10); } - Get hours and minutes from decimal time
function hoursAndMinutes(value) { return [Math.floor(value), Math.floor((value * 60) % 60)]; } - Get the timezone string
function getTimezone() { return Intl.DateTimeFormat().resolvedOptions().timeZone; }
Validator 47 lines
- Check whether all values are equal
function allEqual(values) { return values.every(value => Object.is(value, values[0])); } - Check whether an object is empty
function isEmpty(value) { return Object.keys(value).length === 0; } - Check whether an integer is even
function isEven(value) { return value % 2 === 0; } - Check a leap year
function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } - Check if a character is a digit
function isDigit(char) { return /^[0-9]$/.test(char); } - Check if a date is a weekend
function isWeekend(date) { return new Date(date).getUTCDay() % 6 === 0; } - Check if a flat array has duplicate values
function hasDuplicates(values) { return new Set(values).size !== values.length; } - Check if a date is between two dates
function isBetween({ date, min, max }) { const time = Date.parse(date); return time >= Date.parse(min) && time <= Date.parse(max); } - Check if a date is today
function isToday({ dateTime, now }) { return new Date(dateTime).toISOString().slice(0, 10) === new Date(now).toISOString().slice(0, 10); } - Check if a date occurs in the current year
function isCurrentYear({ dateTime, now }) { return new Date(dateTime).getUTCFullYear() === new Date(now).getUTCFullYear(); } - Check if a given integer is a prime number
function isPrime(n) { if (n < 2) return false; for (let i = 2; i * i <= n; i++) if (n % i === 0) return false; return true; } - Check if a number is positive
function isPositive(n) { return Math.sign(n) === 1; } - Check if a string contains upper case characters
function containsUpperCase(text) { return text !== text.toLowerCase(); } - Check if a date is a weekday
function isWeekday(date) { return new Date(date).getUTCDay() % 6 !== 0; } - Check if a number is a power of 2
function isPowerOfTwo(n) { return n > 0 && (n & (n - 1)) === 0; } - Check if a number is negative
function isNegative(n) { return n < 0; } - Check if a string contains only letters and numbers
function isAlphanumeric(text) { return /^[0-9A-Z]+$/i.test(text); } - Check if a string is a MongoDB ObjectId
function isMongoId(text) { return /^[0-9a-f]{24}$/i.test(text); } - Check if a string is upper case
function isUpperCase(text) { return text === text.toUpperCase(); } - Check if all array elements are equal to a given value
function isEqual({ values, value }) { return values.every(item => item === value); } - Check if a number is in a given range
function inRange({ value, a, b, threshold = 0 }) { return Math.min(a, b) - threshold <= value && value <= Math.max(a, b) + threshold; } - Check if a number is odd
function isOdd(n) { return n % 2 !== 0; } - Check if a string contains lower case characters
function containsLowerCase(text) { return text !== text.toUpperCase(); } - Check if a string contains only ASCII characters
function isAscii(text) { return /^[\x00-\x7F]+$/.test(text); } - Check if a string contains only digits
function isNumeric(text) { return /^[0-9]+$/.test(text); } - Check if a string contains only letters
function isAlpha(text) { return /^[A-Z]+$/i.test(text); } - Check if a string is a hexadecimal color
function isHexColor(color) { return /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color); } - Check if a string is a hexadecimal number
function isHexadecimal(text) { return /^[0-9a-f]+$/i.test(text); } - Check if a string is an octal number
function isOctal(text) { return /^(0o)?[0-7]+$/i.test(text); } - Check if a string is lower case
function isLowerCase(text) { return text === text.toLowerCase(); } - Check if a value is a business identifier code
function isBic(value) { return /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value); } - Check if a value is a plain object
function isPlainObject(value) { return value !== null && typeof value === 'object' && [null, Object.prototype].includes(Object.getPrototypeOf(value)); } - Check if a value is a string
function isString(value) { return Object.prototype.toString.call(value) === '[object String]'; } - Check if a value is base32 encoded
function isBase32(value) { return value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value); } - Check if a value is base58 encoded
function isBase58(value) { return /^[A-HJ-NP-Za-km-z1-9]*$/.test(value); } - Check if a value is nil
function isNil(value) { return value == null; } - Check if an array is not empty
function isNotEmpty(value) { return Array.isArray(value) && value.length > 0; } - Check if an array is a subset of another array
function isSubset({ subset, of }) { const all = new Set(of); return subset.every(value => all.has(value)); } - Validate a Gregorian date
function isValidDate({ year, month, day }) { const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); return day >= 1 && day <= [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]; } - Check if a string contains whitespace
function containsWhitespace(text) { return /\s/.test(text); } - Check if a value is a number
function isNumber(value) { return !isNaN(parseFloat(value)) && isFinite(value); } - Check if a value is an object
function isObject(value) { return value !== null && typeof value === 'object'; } - Check if a value is base64 encoded
function isBase64(value) { return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value); } - Check if an object is an array
function isArray(value) { return Array.isArray(value); } - Check if a value is a regular expression
function isRegExp(value) { return Object.prototype.toString.call(value) === '[object RegExp]'; } - Check if an array contains a value matching some criterias
function contains(values, predicate) { return values.some(predicate); } - Check if an object is a Promise
function isPromise(value) { return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function'; }
Math 14 lines
- Convert degrees to radians
function degreesToRadians(degrees) { return degrees * Math.PI / 180; } - Check if a rectangle contains another one
function contains({ a, b }) { return a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2; } - Check if a rectangle overlaps another one
function overlaps({ a, b }) { return a.x1 < b.x2 && b.x1 < a.x2 && a.y1 < b.y2 && b.y1 < a.y2; } - Calculate the angle of a line defined by two points
function angle({ p1, p2, unit = 'radians' }) { const radians = Math.atan2(p2.y - p1.y, p2.x - p1.x); return unit === 'degrees' ? radians * 180 / Math.PI : radians; } - Calculate the distance between two points
function distance({ p1, p2 }) { return Math.hypot(p2.x - p1.x, p2.y - p1.y); } - Calculate the linear interpolation between two numbers
function lerp({ a, b, amount }) { return (1 - amount) * a + amount * b; } - Normalize the ratio of a number in a range
function normalizeRatio({ value, min, max }) { return (value - min) / (max - min); } - Calculate the midpoint between two points
function midpoint({ p1, p2 }) { return [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2]; } - Check if a point is inside a rectangle
function isInside({ point, rect }) { return point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom; } - Round a number to the nearest multiple of a given value
function roundNearest({ value, nearest }) { return Math.round(value / nearest) * nearest; } - Convert radians to degrees
function radiansToDegrees(radians) { return radians * 180 / Math.PI; } - Calculate the midpoint of a given range
function rangeMidpoint([from, to]) { return (from + to) / 2; } - Linear scale a number between ranges
function linearScale({ value, inMin, inMax, outMin, outMax }) { return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin; } - Linear scale of a number between two ranges
function scale({ value, from, to }) { return ((value - from[0]) * (to[1] - to[0])) / (from[1] - from[0]) + to[0]; }
Function 17 lines
- Logical xor operator
function xor([a, b]) { return Boolean(a) !== Boolean(b); } - Identity function
function identity(value) { return value; } - Box handler
function boxHandler(value) { return { next: f => boxHandler(f(value)), done: f => f(value) }; } - Check if a value is a function
function isFunction(value) { return typeof value === 'function'; } - Check if a value is a generator function
function isGeneratorFunction(value) { return ['[object GeneratorFunction]', '[object AsyncGeneratorFunction]'].includes(Object.prototype.toString.call(value)); } - Check if a value is an async function
function isAsyncFunction(value) { return Object.prototype.toString.call(value) === '[object AsyncFunction]'; } - Compose functions from left to right
function pipe(...fns) { return input => fns.reduce((value, fn) => fn(value), input); } - Compose functions
function compose(...fns) { return input => fns.reduceRight((value, fn) => fn(value), input); } - Create a function that accepts a single argument
function unary(fn) { return value => fn(value); } - Create an empty function
function noop() {} - Curry a function
function curry(fn, ...args) { return fn.length <= args.length ? fn(...args) : (...more) => curry(fn, ...args, ...more); } - Delay the evaluation of a function
function thunkify(fn) { return (...args) => () => fn(...args); } - Execute a function once
function once(fn) { let done = false, result; return (...args) => { if (!done) { result = fn(...args); done = true; } return result; }; } - Flip the arguments of a function
function flip(fn) { return (...args) => fn(...args.reverse()); } - Memoize a function
function memoize(fn) { const cache = new Map(); return arg => { if (!cache.has(arg)) cache.set(arg, fn(arg)); return cache.get(arg); }; } - Partially apply a function
function partial(fn, ...preset) { return (...rest) => fn(...preset, ...rest); } - Uncurry a function
function uncurry(fn, depth = 1) { return (...args) => args.slice(0, depth).reduce((next, arg) => next(arg), fn); }
Random 17 lines
- Generate a random boolean
function randomBoolean() { return Math.random() < 0.5; } - Generate a random floating point number in given range
function randomFloat(min, max) { return Math.random() * (max - min) + min; } - Generate a random hex color
function randomColor() { return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0')}`; } - Generate a random integer in given range
function randomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } - Generate a random IP address
function randomDocumentationIp() { const networks = ['192.0.2', '198.51.100', '203.0.113']; return `${networks[Math.floor(Math.random() * networks.length)]}.${Math.floor(Math.random() * 254) + 1}`; } - Generate a random sign
function randomSign() { return Math.random() < 0.5 ? -1 : 1; } - Generate a random string from given characters
function randomString(length, alphabet) { if (alphabet.length < 2 || alphabet.length > 256) throw new RangeError('alphabet must have 2 to 256 characters'); const limit = 256 - (256 % alphabet.length); let result = ''; while (result.length < length) { for (const byte of crypto.getRandomValues(new Uint8Array(length))) { if (byte < limit && result.length < length) result += alphabet[byte % alphabet.length]; } } return result; } - Generate a random string using Node crypto module
import { randomBytes } from 'node:crypto'; function randomToken(bytes = 32) { return randomBytes(bytes).toString('hex'); } - Generate a random string with given length
function randomId(length) { const alphabet = '0123456789abcdefghjkmnpqrstvwxyz'; return Array.from(crypto.getRandomValues(new Uint8Array(length)), byte => alphabet[byte % 32]).join(''); } - Generate a random UUID
function uuid() { return crypto.randomUUID(); } - Generate a weighted random number in given range
function weightedRandom(min, max) { return Math.floor(Math.random() ** 2 * (max - min)) + min; } - Generate an array of random integers in a given range
function randomIntegers(min, max, count) { return Array.from({ length: count }, () => Math.floor(Math.random() * (max - min + 1)) + min); } - Get a random item and remove it from an array
function takeRandomItem(values) { return values.splice(Math.floor(Math.random() * values.length), 1)[0]; } - Get a random item from an array
function randomItem(values) { return values[Math.floor(Math.random() * values.length)]; } - Get random items of an array
function randomItems(values, count) { const pool = [...values]; for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; } return pool.slice(0, count); } - Pick a random property of an object
function randomKey(object) { const keys = Object.keys(object); return keys[Math.floor(Math.random() * keys.length)]; } - Pick random lines from a text document
function randomLines(text, count) { const lines = text.split(/\r?\n/); for (let i = lines.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [lines[i], lines[j]] = [lines[j], lines[i]]; } return lines.slice(0, count); }
DOM 30 lines
- Check if a given DOMRect is contained within another DOMRect
function isContained({ target, container }) { return target.x >= container.x && target.x + target.width <= container.x + container.width && target.y >= container.y && target.y + target.height <= container.y + container.height; } - Check if two DOMRects intersect
function intersect({ a, b }) { return b.x <= a.x + a.width && b.x + b.width >= a.x && b.y <= a.y + a.height && b.y + b.height >= a.y; } - Compare two DOMRects for size and position match
function sameRect({ a, b }) { return ['x', 'y', 'width', 'height'].every(key => a[key] === b[key]); } - Get the center point of a DOMRect
function getCenter({ x, y, width, height }) { return [x + width / 2, y + height / 2]; } - Calculate the distance to the bottom of a page
function distanceToBottom() { return document.documentElement.scrollHeight - window.innerHeight - window.scrollY; } - Check if an element has CSS overflow
function hasCssOverflow(element) { const { overflowX, overflowY } = getComputedStyle(element); return [overflowX, overflowY].some(value => ['auto', 'scroll'].includes(value)); } - Check if an element has overflow
function hasOverflow(element) { return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth; } - Check if an element is a descendant of another
function isDescendant(child, parent) { return child !== parent && parent.contains(child); } - Check if an element is focused
function hasFocus(element) { return element === document.activeElement; } - Check if the touch events are supported
function touchSupported() { return 'ontouchstart' in window || navigator.maxTouchPoints > 0; } - Check if user scrolls to the bottom of the page
function isAtBottom(tolerance = 1) { const { scrollHeight, clientHeight } = document.documentElement; return scrollHeight - clientHeight - window.scrollY <= tolerance; } - Detect Internet Explorer browser
function isInternetExplorer() { return 'documentMode' in document; } - Detect macOS browser
function isApplePlatform() { return /Mac|iPhone|iPad|iPod/.test(navigator.userAgentData?.platform ?? navigator.platform); } - Get all siblings of an element
function siblings(element) { return element.parentElement ? [...element.parentElement.children].filter(child => child !== element) : []; } - Get the position of an element relative to the document
function getPosition(element) { const rect = element.getBoundingClientRect(); return { left: rect.left + window.scrollX, top: rect.top + window.scrollY }; } - Get the selected text
function getSelectedText() { return window.getSelection()?.toString() ?? ''; } - Go back to the previous page
function goBack() { history.back(); } - Hide an element
function hide(element) { element.hidden = true; } - Insert an element after other one
function insertAfter(element, reference) { reference.after(element); } - Insert an element before other one
function insertBefore(element, reference) { reference.before(element); } - Insert given HTML after an element
function insertHtmlAfter(html, element) { element.insertAdjacentHTML('afterend', html); } - Insert given HTML before an element
function insertHtmlBefore(html, element) { element.insertAdjacentHTML('beforebegin', html); } - Redirect to another page
function goTo(url) { location.assign(url); } - Reload the current page
function reload() { location.reload(); } - Replace an element
function replace(element, replacement) { element.replaceWith(replacement); } - Scroll to top of the page
function goToTop() { window.scrollTo(0, 0); } - Serialize form data
function serialize(form) { const groups = new Map(); for (const [key, value] of new FormData(form)) groups.set(key, [...(groups.get(key) ?? []), value]); return Object.fromEntries([...groups].map(([key, values]) => [key, values.length > 1 ? values : values[0]])); } - Show an element
function show(element) { element.hidden = false; element.style.removeProperty('display'); } - Strip HTML from a given text
function stripHtml(html) { return new DOMParser().parseFromString(html, 'text/html').body.textContent ?? ''; } - Toggle an element
function toggle(element) { element.hidden = !element.hidden; }
Misc 28 lines
- Convert Celsius to Fahrenheit
function toFahrenheit(value) { return value * 9 / 5 + 32; } - Convert hex to RGB
function hexToRgb(hex) { return hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`).substring(1).match(/.{2}/g).map(channel => parseInt(channel, 16)); } - Convert URL parameters to object
function getUrlParams(query) { return Array.from(new URLSearchParams(query)).reduce((params, [key, value]) => Object.assign(params, { [key]: Object.hasOwn(params, key) ? [].concat(params[key], value) : value }), {}); } - Convert 3 digits color to 6 digits color
function toFullHexColor(color) { return `#${(color.startsWith('#') ? color.slice(1) : color).split('').map(digit => `${digit}${digit}`).join('')}`; } - Convert Fahrenheit to Celsius
function fahrenheitToCelsius(fahrenheit) { return (fahrenheit - 32) * 5 / 9; } - Get the value of a param from a URL
function getParam({ url, param }) { return new URL(url).searchParams.get(param); } - Convert RGB color to hex
function rgbToHex({ red, green, blue }) { return `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`; } - Convert cookie to object
function parseCookies(cookie) { return Object.fromEntries(cookie.split(';').filter(item => item.includes('=')).map(item => [item.slice(0, item.indexOf('=')).trim(), item.slice(item.indexOf('=') + 1).trim()])); } - Easing functions
function ease({ name, t }) { return { linear: t, easeInQuad: t * t, easeOutQuad: t * (2 - t), easeInOutQuad: t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t, easeInCubic: t ** 3, easeOutCubic: (t - 1) ** 3 + 1 }[name]; } - Encode a URL component strictly
function encodeStrict(value) { return encodeURIComponent(value).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`); } - Get the value of a cookie
function getCookie({ cookie, name }) { const match = `; ${cookie}`.split(`; ${name}=`); return match.length > 1 ? match.pop().split(';').shift() : null; } - Get the type of a variable as a string
function getTypeOf(value) { return Object.prototype.toString.call(value).match(/\[object (.*)\]/)[1]; } - Swap two variables
function swap([a, b]) { [a, b] = [b, a]; return [a, b]; } - Decode a JWT token
function decodeJwtPayload(token) { const base64 = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'); return JSON.parse(decodeURIComponent(Array.from(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, '=')), char => `%${char.charCodeAt(0).toString(16).padStart(2, '0')}`).join(''))); } - Get the first defined and non-null value
function coalesce(values) { return values.find(item => item !== undefined && item !== null) ?? null; } - Convert a Lab color to an LCH color
function labToLch([l, a, b]) { return [l, Math.hypot(a, b), ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360]; } - Convert an LCH color to a Lab color
function lchToLab([l, c, h]) { return [l, Math.cos((h * Math.PI) / 180) * c, Math.sin((h * Math.PI) / 180) * c]; } - Check if the code is running in Jest
function isRunningInJest() { return typeof process !== 'undefined' && process.env.JEST_WORKER_ID !== undefined; } - Check if the code is running in NodeJS
function isNode() { return typeof process !== 'undefined' && process.versions?.node != null; } - Check if the code is running in the browser
function isBrowser() { return typeof window === 'object' && typeof document === 'object'; } - Clear all cookies
function clearCookies() { for (const cookie of document.cookie.split(';')) { const name = cookie.split('=')[0].trim(); if (name) document.cookie = `${name}=; Max-Age=0; path=/`; } } - Detect dark mode
function isDarkMode() { return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false; } - Emulate a dice throw
function throwDice() { return Math.floor(Math.random() * 6) + 1; } - Generate an unique and increment id
function createIdGenerator(start = 0) { let id = start; return () => id++; } - Redirect the page to HTTPS if it is in HTTP
function redirectToHttps() { if (location.protocol !== 'http:') return; const url = new URL(location.href); url.protocol = 'https:'; location.replace(url); } - Run Promises in sequence
async function runInSequence(tasks) { const results = []; for (const task of tasks) results.push(await task()); return results; } - Wait for an amount of time
function wait(milliseconds) { return new Promise(resolve => setTimeout(resolve, milliseconds)); } - Wait for the next event loop
function nextTask() { return new Promise(resolve => setTimeout(resolve, 0)); }
Email 10 lines
- Convert an email domain to punycodeby Oveyon
function toAsciiAddress(address) { const at = address.lastIndexOf('@'); return `${address.slice(0, at)}@${new URL(`http://${address.slice(at + 1)}`).hostname}`; } - Get the domain of an email addressby Oveyon
function emailDomain(address) { return address.slice(address.lastIndexOf('@') + 1).toLowerCase(); } - Mask an email address for logsby Oveyon
function maskEmail(address) { return `${address.slice(0, 1)}•••${address.slice(address.lastIndexOf('@'))}`; } - Normalize an email address for comparisonby Oveyon
function normalizeEmail(address) { const value = address.trim(); const at = value.lastIndexOf('@'); return `${value.slice(0, at)}@${value.slice(at + 1).toLowerCase()}`; } - Read a Retry-After headerby Oveyon
function retryAfterMs({ retryAfter, date }) { const seconds = Number(retryAfter); return Math.max(0, Number.isFinite(seconds) ? seconds * 1000 : Date.parse(retryAfter) - Date.parse(date)); } - Compute a backoff delay with full jitterby Oveyon
function backoffMs({ attempt, baseMs, capMs, random }) { return Math.round(random * Math.min(capMs, baseMs * 2 ** attempt)); } - Build an idempotency key from an eventby Oveyon
function idempotencyKey({ scope, id, version }) { return [scope, id, version].map(part => encodeURIComponent(String(part))).join(':'); } - Classify an SMTP replyby Oveyon
function classifySmtpReply(reply) { const [, code, enhanced] = /^([2-5]\d{2})(?:[ -]([245]\.\d{1,3}\.\d{1,3}))?/.exec(reply); return { code: Number(code), enhanced: enhanced || null, outcome: { 2: 'success', 3: 'intermediate', 4: 'transient', 5: 'permanent' }[code[0]], retry: code[0] === '4' }; } - Build a DMARC recordby Oveyon
function dmarcRecord({ policy, rua }) { return ['v=DMARC1', `p=${policy}`, ...(rua ? [`rua=${rua}`] : [])].join('; '); } - Parse a DMARC recordby Oveyon
function parseDmarc(record) { return Object.fromEntries(record.split(';').map(tag => tag.trim()).filter(Boolean).map(tag => [tag.slice(0, tag.indexOf('=')).trim().toLowerCase(), tag.slice(tag.indexOf('=') + 1).trim()])); }
Each entry is the implementation the local lab or the tests execute. Most are adapted from the original 1loc collection by Nguyen Huu Phuoc and contributors (MIT); the email lines are written by Oveyon (MIT). Read every utility’s limits before using it with untrusted input. Sources and licenses.