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.

Also as one compact file · .md

Array 50 lines

  1. Clone an arrayfunction clone(values) { return [...values]; }
  2. Remove duplicate valuesfunction unique(values) { return [...new Set(values)]; }
  3. Flatten a nested arrayfunction flatten(values) { return values.flat(Infinity); }
  4. Split an array into chunksfunction chunk({ values, size }) { return Array.from({ length: Math.ceil(values.length / size) }, (_, i) => values.slice(i * size, (i + 1) * size)); }
  5. Find the intersection of arraysfunction intersection({ left, right }) { const other = new Set(right); return [...new Set(left)].filter(value => other.has(value)); }
  6. Sort numbers in ascending orderfunction sortNumbers(values) { return [...values].sort((a, b) => a - b); }
  7. Sum an array of numbersfunction sum(values) { return values.reduce((total, value) => total + value, 0); }
  8. Group objects by a keyfunction 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); }
  9. Cast a value as an arrayfunction castArray(value) { return Array.isArray(value) ? value : [value]; }
  10. Convert an array of strings to numbersfunction toNumbers(values) { return values.map(Number); }
  11. Get all subsets of an arrayfunction getSubsets(values) { return values.reduce((subsets, value) => subsets.concat(subsets.map(subset => [...subset, value])), [[]]); }
  12. Get union of arraysfunction union(arrays) { return [...new Set(arrays.flat())]; }
  13. Swap the rows and columns of a matrixfunction transpose(matrix) { return matrix[0].map((_, column) => matrix.map(row => row[column])); }
  14. Swap two array itemsfunction swapItems({ values, i, j }) { const copy = [...values]; [copy[i], copy[j]] = [copy[j], copy[i]]; return copy; }
  15. Unzip an array of arraysfunction 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])); }
  16. Compare two arraysfunction isEqual({ a, b }) { return a.length === b.length && a.every((value, i) => Object.is(value, b[i])); }
  17. Convert an array of objects to a single objectfunction toObject({ values, key }) { return Object.fromEntries(values.map(item => [item[key], item])); }
  18. Count the occurrences of a value in an arrayfunction countOccurrences({ values, value }) { return values.filter(item => item === value).length; }
  19. Count the occurrences of array elementsfunction countEach(values) { return { ...values.reduce((counts, value) => ((counts[value] = (counts[value] || 0) + 1), counts), Object.create(null)) }; }
  20. Create an array of numbers in the given rangefunction range({ min, max }) { return Array.from({ length: max - min + 1 }, (_, i) => min + i); }
  21. Create cartesian productfunction cartesian(sets) { return sets.reduce((product, set) => product.flatMap(prefix => set.map(item => [...prefix, item])), [[]]); }
  22. Find the minimum item of an arrayfunction min(values) { return Math.min(...values); }
  23. Get the rank of an array of numbersfunction ranking(values) { return values.map(value => values.filter(other => other > value).length + 1); }
  24. Remove falsy values from arrayfunction removeFalsy(values) { return values.filter(Boolean); }
  25. Zip multiple arraysfunction zip(arrays) { return Array.from({ length: Math.max(0, ...arrays.map(array => array.length)) }, (_, i) => arrays.map(array => array[i] ?? null)); }
  26. Compare two arrays regardless of orderfunction isEqualIgnoringOrder({ a, b }) { const normalize = values => JSON.stringify([...new Set(values)].sort()); return normalize(a) === normalize(b); }
  27. Count by the properties of an array of objectsfunction countBy({ values, key }) { return { ...values.reduce((counts, item) => ((counts[item[key]] = (counts[item[key]] || 0) + 1), counts), Object.create(null)) }; }
  28. Create an array of cumulative sumfunction accumulate(values) { let total = 0; return values.map(value => (total += value)); }
  29. Find the index of the maximum item of an arrayfunction indexOfMax(values) { return values.reduce((best, value, i) => (value > values[best] ? i : best), 0); }
  30. Find the maximum item of an array by given keyfunction maxBy({ values, key }) { return values.reduce((best, item) => (best === null || item[key] > best[key] ? item : best), null); }
  31. Find the maximum item of an arrayfunction max(values) { return Math.max(...values); }
  32. Generate an array of alphabet charactersfunction alphabet(count) { return Array.from({ length: count }, (_, i) => String.fromCharCode(97 + i)); }
  33. Get all arrays of consecutive elementsfunction windows({ values, size }) { return size > values.length ? [] : values.slice(size - 1).map((_, i) => values.slice(i, i + size)); }
  34. Get indices of a value in an arrayfunction indices({ values, value }) { return values.flatMap((item, i) => (item === value ? [i] : [])); }
  35. Get the average of an arrayfunction average(values) { return values.reduce((sum, value) => sum + value, 0) / values.length; }
  36. Get the unique values of an arrayfunction uniqueValues(values) { return [...new Set(values)]; }
  37. Intersperse element between elementsfunction intersperse({ values, separator }) { return values.flatMap((value, i) => (i === 0 ? [value] : [separator, value])); }
  38. Sort an array of items by given keyfunction sortBy({ values, key }) { return [...values].sort((a, b) => (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0)); }
  39. Check if an array is emptyfunction isEmptyArray(value) { return Array.isArray(value) && !value.length; }
  40. Find the closest number from an arrayfunction closest({ values, target }) { return values.reduce((best, value) => (Math.abs(value - target) < Math.abs(best - target) ? value : best)); }
  41. Find the index of the minimum item of an arrayfunction indexOfMin(values) { return values.reduce((best, value, i) => (value < values[best] ? i : best), 0); }
  42. Find the length of the longest string in an arrayfunction longestLength(words) { return Math.max(0, ...words.map(word => word.length)); }
  43. Find the minimum item of an array by given keyfunction minBy({ values, key }) { return values.reduce((best, item) => (best === null || item[key] < best[key] ? item : best), null); }
  44. Get all nth items of an arrayfunction getNthItems({ values, nth }) { return values.filter((_, i) => i % nth === nth - 1); }
  45. Merge two arraysfunction merge({ a, b, unique = false }) { return unique ? [...new Set([...a, ...b])] : [...a, ...b]; }
  46. Repeat an arrayfunction repeatArray({ values, times }) { return Array(times).fill(values).flat(); }
  47. Empty an arrayfunction empty(values) { values.length = 0; return values; }
  48. Find the index of the last matching item of an arrayfunction lastIndex(values, predicate) { return values.findLastIndex(predicate); }
  49. Partition an array based on a conditionfunction partition(values, predicate) { return values.reduce((groups, value) => (groups[predicate(value) ? 0 : 1].push(value), groups), [[], []]); }
  50. Shuffle an arrayfunction 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

  1. Pick properties from an objectfunction pick({ value, keys }) { return Object.fromEntries(keys.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]])); }
  2. Omit properties from an objectfunction omit({ value, keys }) { return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key))); }
  3. Create an object from pairs of key and valuefunction toObject(pairs) { return Object.fromEntries(pairs); }
  4. Check if multiple objects are equalfunction areEqual(objects) { return objects.every(object => JSON.stringify(object) === JSON.stringify(objects[0])); }
  5. Get the value at given path of an objectfunction getValue({ path, object }) { return path.split('.').reduce((value, key) => (value == null ? undefined : value[key]), object) ?? null; }
  6. Immutably rename object keysfunction renameKeys({ keysMap, object }) { return Object.fromEntries(Object.entries(object).map(([key, value]) => [keysMap[key] || key, value])); }
  7. Invert keys and values of an objectfunction invert(object) { return Object.fromEntries(Object.entries(object).map(([key, value]) => [value, key])); }
  8. Extract values of a property from an array of objectsfunction pluck({ objects, property }) { return objects.map(object => object[property] ?? null); }
  9. Sort an object by its propertiesfunction sortKeys(object) { return Object.fromEntries(Object.keys(object).sort().map(key => [key, object[key]])); }
  10. Remove all null and undefined properties from an objectfunction removeNullish(object) { return Object.fromEntries(Object.entries(object).filter(([, value]) => value != null)); }
  11. Shallow copy an objectfunction shallowCopy(object) { return { ...object }; }
  12. Get unique objects from an array by keyfunction uniqueBy({ objects, key }) { return [...new Map(objects.map(item => [item[key], item])).values()]; }
  13. Create an empty map that does not have propertiesfunction createDictionary() { return Object.create(null); }

String 51 lines

  1. Capitalize a stringfunction capitalize(value) { const [first, ...rest] = Array.from(value); return first ? first.toUpperCase() + rest.join('') : ''; }
  2. Reverse a stringfunction reverse(value) { return Array.from(value).reverse().join(''); }
  3. Check a palindromefunction palindrome(value) { return value === Array.from(value).reverse().join(''); }
  4. Create a simple URL slugfunction slugify(value) { return value.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); }
  5. Convert snake case to camel casefunction camelCase(value) { return value.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()); }
  6. Remove duplicate linesfunction uniqueLines(value) { return [...new Set(value.split(/\r?\n/))].join('\n'); }
  7. Check if a URL is absolutefunction isAbsoluteUrl(url) { return /^[a-z][a-z0-9+.-]*:/i.test(url); }
  8. Check if a path is relativefunction isRelative(path) { return !/^([a-z]+:)?[\\/]/i.test(path); }
  9. Convert a base64 encoded string to an Uint8Arrayfunction base64ToBytes(base64) { return Array.from(atob(base64), char => char.charCodeAt(0)); }
  10. Convert an Uint8Array to a base64 encoded stringfunction bytesToBase64(bytes) { return btoa(String.fromCharCode(...bytes)); }
  11. Check if a string consists of a repeated character sequencefunction consistsRepeatedSubstring(text) { return `${text}${text}`.indexOf(text, 1) !== text.length; }
  12. Check if two strings are anagramsfunction areAnagram({ first, second }) { const sorted = text => Array.from(text.toLowerCase()).sort().join(''); return sorted(first) === sorted(second); }
  13. Convert a letter to its regional indicator emojifunction letterToEmoji(letter) { return String.fromCodePoint(letter.toLowerCase().charCodeAt(0) + 127365); }
  14. Sort the characters of a string in alphabetical orderfunction sortCharacters(text) { return Array.from(text).sort((a, b) => a.localeCompare(b, 'en')).join(''); }
  15. Generate a hash of a stringfunction hashString(text) { return text.split('').reduce((hash, char) => (Math.imul(31, hash) + char.charCodeAt(0)) | 0, 0); }
  16. Get the length of a string in bytesfunction byteLength(text) { return new TextEncoder().encode(text).length; }
  17. Strip ANSI codes from a stringfunction stripAnsi(text) { return text.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, ''); }
  18. Swap case of characters in a stringfunction swapCase(text) { return Array.from(text).map(char => char === char.toLowerCase() ? char.toUpperCase() : char.toLowerCase()).join(''); }
  19. Convert a string to Pascal casefunction toPascalCase(text) { return (text.match(/[a-zA-Z0-9]+/g) || []).map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(''); }
  20. Convert a Windows file path to a Unix pathfunction toUnixPath(path) { return path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, ''); }
  21. Convert camel case to kebab case and vice versafunction convertCase({ value, to }) { return to === 'kebab' ? value.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase() : value.replace(/-./g, match => match[1].toUpperCase()); }
  22. Count the number of words in a stringfunction countWords(text) { return (text.match(/\S+/g) || []).length; }
  23. Get the file extension from a file namefunction fileExtension(name) { const dot = name.lastIndexOf('.'); return dot > 0 ? name.slice(dot + 1) : ''; }
  24. Get the file name from a URLfunction fileNameFromUrl(url) { const path = url.split(/[?#]/)[0]; return path.slice(path.lastIndexOf('/') + 1); }
  25. Get the number of a character in a stringfunction characterCount({ text, char }) { return text.split(char).length - 1; }
  26. Normalize file path slashesfunction normalizePath(path) { return path.replace(/[\\/]+/g, '/'); }
  27. Remove spaces from a stringfunction removeSpaces(text) { return text.replace(/\s/g, ''); }
  28. Repeat a stringfunction repeat({ text, times }) { return text.repeat(times); }
  29. Replace all line breaks with br elementsfunction nl2br(text) { return text.replace(/\r?\n/g, '<br>'); }
  30. Replace all tab characters with spacesfunction tabsToSpaces({ text, spaces }) { return text.replaceAll('\t', ' '.repeat(spaces)); }
  31. Mask the first characters of a stringfunction maskStart({ text, count, mask }) { return text.slice(count).padStart(text.length, mask); }
  32. Reverse the order of lines of a textfunction reverseLines(text) { return text.split(/\r?\n/).reverse().join('\n'); }
  33. Sort lines of a text document in alphabetical orderfunction sortLines(text) { return text.split(/\r?\n/).sort().join('\n'); }
  34. Trim slashes at the beginning and the end of a stringfunction trimSlashes(text) { return text.replace(/^\/+|\/+$/g, ''); }
  35. Trim the file extension from a file namefunction trimExtension(name) { const dot = name.lastIndexOf('.'); return dot > 0 ? name.slice(0, dot) : name; }
  36. Convert a string to camel casefunction toCamelCase(text) { return text.trim().replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : ''); }
  37. Convert the name of an Excel column to a numberfunction columnNumber(column) { return column.split('').reduce((total, letter) => total * 26 + parseInt(letter, 36) - 9, 0); }
  38. Count the occurrences of a character in a stringfunction countOccurrences({ text, char }) { return Array.from(text).filter(item => item === char).length; }
  39. Decapitalize a stringfunction decapitalize(text) { const [first = '', ...rest] = Array.from(text); return first.toLowerCase() + rest.join(''); }
  40. Escape HTML special charactersfunction escapeHtml(text) { return text.replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]); }
  41. Format a stringfunction format({ template, values }) { return values.reduce((text, value, i) => text.replaceAll(`{${i}}`, String(value)), template); }
  42. Get the base URL without any parametersfunction baseUrl(url) { return url.split(/[?#]/)[0]; }
  43. Make the first character of a string lowercasefunction lowercaseFirst(text) { return `${text.charAt(0).toLowerCase()}${text.slice(1)}`; }
  44. Prepend a line number to each line of a text documentfunction prependNumbers(text) { return text.split(/\r?\n/).map((line, i) => `${String(i + 1).padStart(2, ' ')} ${line}`).join('\n'); }
  45. Replace multiple spaces with a single spacefunction collapseSpaces(text) { return text.replace(/\s\s+/g, ' '); }
  46. Trim a character from both endsfunction trimCharacter({ text, char }) { const escaped = char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return text.replace(new RegExp(`^(?:${escaped})+|(?:${escaped})+$`, 'g'), ''); }
  47. Truncate a string at full wordsfunction 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}`; }
  48. Unescape HTML special charactersfunction unescapeHtml(text) { return text.replace(/&(?:amp|lt|gt|quot|#0*39);/g, entity => ({ '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"' })[entity] ?? "'"); }
  49. Uppercase the first character of each wordfunction uppercaseWords(text) { return text.split(' ').map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(' '); }
  50. Remove empty lines of a text documentfunction removeEmptyLines(text) { return text.split(/\r?\n/).filter(line => line.trim() !== '').join('\n'); }
  51. Decode numeric HTML entitiesfunction 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

  1. Clamp a number to a rangefunction clamp({ value, min, max }) { return Math.min(max, Math.max(min, value)); }
  2. Round to a number of digitsfunction roundTo({ value, digits }) { const factor = 10 ** digits; return Math.round(value * factor) / factor; }
  3. Add an ordinal suffix to a numberfunction addOrdinal(n) { return `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`; }
  4. Calculate Fibonacci numbersfunction fibonacci(n, memo = {}) { return memo[n] || (n <= 2 ? 1 : (memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo))); }
  5. Calculate the division of numbersfunction division(values) { return values.reduce((a, b) => a / b); }
  6. Calculate the mod of a collection indexfunction mod({ index, length }) { return ((index % length) + length) % length; }
  7. Compute the greatest common divisor between two numbersfunction gcd({ a, b }) { return b === 0 ? Math.abs(a) : gcd({ a: b, b: a % b }); }
  8. Calculate the average of numbersfunction averageOf(values) { return values.reduce((a, b) => a + b) / values.length; }
  9. Calculate the remainder of division of numbersfunction remainder(values) { return values.reduce((a, b) => a % b); }
  10. Subtract numbersfunction subtract(values) { return values.reduce((a, b) => a - b); }
  11. Calculate the factorial of a numberfunction factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); }
  12. Calculate the sum of numbersfunction sumOf(values) { return values.reduce((a, b) => a + b); }
  13. Convert a number to equivalent charactersfunction toChars(n) { return `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`; }
  14. Multiply numbersfunction multiply(values) { return values.reduce((a, b) => a * b); }
  15. Truncate a number at decimalfunction truncate(n) { return Math.trunc(n); }
  16. Convert a string to a numberfunction toNumber(text) { return +text; }
  17. Convert decimal to binary recursivelyfunction decToBinary(num) { return num === 0 ? 0 : (num % 2) + 10 * decToBinary(Math.floor(num / 2)); }
  18. Prefix an integer with zerosfunction prefixWithZeros({ n, length }) { return String(n).padStart(length, '0'); }
  19. Truncate a number to decimal places without roundingfunction toFixedDown({ n, digits }) { return Number(`${n}`.match(new RegExp(`^-?\\d+(?:\\.\\d{0,${digits}})?`))[0]); }
  20. Wrap a number between two valuesfunction wrap({ num, min, max }) { return ((((num - min) % (max - min)) + (max - min)) % (max - min)) + min; }
  21. Get the arrays of digits from a numberfunction digitize(n) { return [...`${n}`].map(digit => Number(digit)); }
  22. Get the intersection range between two rangesfunction 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

  1. Compare two datesfunction compareDates({ first, second }) { return Math.sign(new Date(first).getTime() - new Date(second).getTime()); }
  2. Add AM PM suffix to an hourfunction suffixAmPm(hour) { return `${hour % 12 === 0 ? 12 : hour % 12}${hour < 12 ? 'am' : 'pm'}`; }
  3. Calculate the number of days between two datesfunction diffDays({ first, second }) { return Math.round(Math.abs(Date.parse(second) - Date.parse(first)) / 86400000); }
  4. Convert a date to YYYY-MM-DD formatfunction formatYmd(dateTime) { return new Date(dateTime).toISOString().slice(0, 10); }
  5. Convert seconds to hh:mm:ss formatfunction formatSeconds(seconds) { return [Math.floor(seconds / 3600), Math.floor(seconds % 3600 / 60), seconds % 60].map(part => String(part).padStart(2, '0')).join(':'); }
  6. Calculate the number of months between two datesfunction 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()); }
  7. Extract year, month, day, hour, minute, second and millisecond from a datefunction extract(dateTime) { return new Date(dateTime).toISOString().split(/[^0-9]/).slice(0, -1); }
  8. Get the current timestamp in secondsfunction unixSeconds(now) { return Math.floor(Date.parse(now) / 1000); }
  9. Get the first date in the month of a datefunction firstDateOfMonth(date) { const d = new Date(date); d.setUTCDate(1); return d.toISOString().slice(0, 10); }
  10. Get the total number of days in a yearfunction daysInYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365; }
  11. Set the time of a date to midnightfunction midnightUtc(now) { const d = new Date(now); d.setUTCHours(0, 0, 0, 0); return d.toISOString(); }
  12. Format a date for the given localefunction formatDate({ date, locale }) { return new Intl.DateTimeFormat(locale, { timeZone: 'UTC' }).format(new Date(date)); }
  13. Get the current quarter of a datefunction quarter(date) { return Math.ceil((new Date(date).getUTCMonth() + 1) / 3); }
  14. Get the day of the year from a datefunction dayOfYear(date) { return Math.round((Date.parse(date) - Date.parse(`${date.slice(0, 4)}-01-01`)) / 86400000) + 1; }
  15. Get the last date in the month of a datefunction lastDateOfMonth(date) { const d = new Date(date); d.setUTCMonth(d.getUTCMonth() + 1, 0); return d.toISOString().slice(0, 10); }
  16. Get the month name of a datefunction monthName(date) { return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][new Date(date).getUTCMonth()]; }
  17. Get the tomorrow datefunction tomorrow(date) { const d = new Date(date); d.setUTCDate(d.getUTCDate() + 1); return d.toISOString().slice(0, 10); }
  18. Get the weekday of a datefunction weekday(date) { return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][new Date(date).getUTCDay()]; }
  19. Sort an array of datesfunction sortDates({ dates, order = 'asc' }) { const sorted = [...dates].sort((a, b) => Date.parse(a) - Date.parse(b)); return order === 'desc' ? sorted.reverse() : sorted; }
  20. Determine one year from a datefunction plusOneYear(date) { const d = new Date(date); d.setUTCFullYear(d.getUTCFullYear() + 1); return d.toISOString().slice(0, 10); }
  21. Get the number of days in a given monthfunction daysInMonth({ year, month }) { const d = new Date(0); d.setUTCFullYear(year, month, 0); return d.getUTCDate(); }
  22. Get the yesterday datefunction yesterday(date) { const d = new Date(date); d.setUTCDate(d.getUTCDate() - 1); return d.toISOString().slice(0, 10); }
  23. Get hours and minutes from decimal timefunction hoursAndMinutes(value) { return [Math.floor(value), Math.floor((value * 60) % 60)]; }
  24. Get the timezone stringfunction getTimezone() { return Intl.DateTimeFormat().resolvedOptions().timeZone; }

Validator 47 lines

  1. Check whether all values are equalfunction allEqual(values) { return values.every(value => Object.is(value, values[0])); }
  2. Check whether an object is emptyfunction isEmpty(value) { return Object.keys(value).length === 0; }
  3. Check whether an integer is evenfunction isEven(value) { return value % 2 === 0; }
  4. Check a leap yearfunction isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }
  5. Check if a character is a digitfunction isDigit(char) { return /^[0-9]$/.test(char); }
  6. Check if a date is a weekendfunction isWeekend(date) { return new Date(date).getUTCDay() % 6 === 0; }
  7. Check if a flat array has duplicate valuesfunction hasDuplicates(values) { return new Set(values).size !== values.length; }
  8. Check if a date is between two datesfunction isBetween({ date, min, max }) { const time = Date.parse(date); return time >= Date.parse(min) && time <= Date.parse(max); }
  9. Check if a date is todayfunction isToday({ dateTime, now }) { return new Date(dateTime).toISOString().slice(0, 10) === new Date(now).toISOString().slice(0, 10); }
  10. Check if a date occurs in the current yearfunction isCurrentYear({ dateTime, now }) { return new Date(dateTime).getUTCFullYear() === new Date(now).getUTCFullYear(); }
  11. Check if a given integer is a prime numberfunction isPrime(n) { if (n < 2) return false; for (let i = 2; i * i <= n; i++) if (n % i === 0) return false; return true; }
  12. Check if a number is positivefunction isPositive(n) { return Math.sign(n) === 1; }
  13. Check if a string contains upper case charactersfunction containsUpperCase(text) { return text !== text.toLowerCase(); }
  14. Check if a date is a weekdayfunction isWeekday(date) { return new Date(date).getUTCDay() % 6 !== 0; }
  15. Check if a number is a power of 2function isPowerOfTwo(n) { return n > 0 && (n & (n - 1)) === 0; }
  16. Check if a number is negativefunction isNegative(n) { return n < 0; }
  17. Check if a string contains only letters and numbersfunction isAlphanumeric(text) { return /^[0-9A-Z]+$/i.test(text); }
  18. Check if a string is a MongoDB ObjectIdfunction isMongoId(text) { return /^[0-9a-f]{24}$/i.test(text); }
  19. Check if a string is upper casefunction isUpperCase(text) { return text === text.toUpperCase(); }
  20. Check if all array elements are equal to a given valuefunction isEqual({ values, value }) { return values.every(item => item === value); }
  21. Check if a number is in a given rangefunction inRange({ value, a, b, threshold = 0 }) { return Math.min(a, b) - threshold <= value && value <= Math.max(a, b) + threshold; }
  22. Check if a number is oddfunction isOdd(n) { return n % 2 !== 0; }
  23. Check if a string contains lower case charactersfunction containsLowerCase(text) { return text !== text.toUpperCase(); }
  24. Check if a string contains only ASCII charactersfunction isAscii(text) { return /^[\x00-\x7F]+$/.test(text); }
  25. Check if a string contains only digitsfunction isNumeric(text) { return /^[0-9]+$/.test(text); }
  26. Check if a string contains only lettersfunction isAlpha(text) { return /^[A-Z]+$/i.test(text); }
  27. Check if a string is a hexadecimal colorfunction isHexColor(color) { return /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color); }
  28. Check if a string is a hexadecimal numberfunction isHexadecimal(text) { return /^[0-9a-f]+$/i.test(text); }
  29. Check if a string is an octal numberfunction isOctal(text) { return /^(0o)?[0-7]+$/i.test(text); }
  30. Check if a string is lower casefunction isLowerCase(text) { return text === text.toLowerCase(); }
  31. Check if a value is a business identifier codefunction isBic(value) { return /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value); }
  32. Check if a value is a plain objectfunction isPlainObject(value) { return value !== null && typeof value === 'object' && [null, Object.prototype].includes(Object.getPrototypeOf(value)); }
  33. Check if a value is a stringfunction isString(value) { return Object.prototype.toString.call(value) === '[object String]'; }
  34. Check if a value is base32 encodedfunction isBase32(value) { return value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value); }
  35. Check if a value is base58 encodedfunction isBase58(value) { return /^[A-HJ-NP-Za-km-z1-9]*$/.test(value); }
  36. Check if a value is nilfunction isNil(value) { return value == null; }
  37. Check if an array is not emptyfunction isNotEmpty(value) { return Array.isArray(value) && value.length > 0; }
  38. Check if an array is a subset of another arrayfunction isSubset({ subset, of }) { const all = new Set(of); return subset.every(value => all.has(value)); }
  39. Validate a Gregorian datefunction 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]; }
  40. Check if a string contains whitespacefunction containsWhitespace(text) { return /\s/.test(text); }
  41. Check if a value is a numberfunction isNumber(value) { return !isNaN(parseFloat(value)) && isFinite(value); }
  42. Check if a value is an objectfunction isObject(value) { return value !== null && typeof value === 'object'; }
  43. Check if a value is base64 encodedfunction 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); }
  44. Check if an object is an arrayfunction isArray(value) { return Array.isArray(value); }
  45. Check if a value is a regular expressionfunction isRegExp(value) { return Object.prototype.toString.call(value) === '[object RegExp]'; }
  46. Check if an array contains a value matching some criteriasfunction contains(values, predicate) { return values.some(predicate); }
  47. Check if an object is a Promisefunction isPromise(value) { return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function'; }

Math 14 lines

  1. Convert degrees to radiansfunction degreesToRadians(degrees) { return degrees * Math.PI / 180; }
  2. Check if a rectangle contains another onefunction contains({ a, b }) { return a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2; }
  3. Check if a rectangle overlaps another onefunction overlaps({ a, b }) { return a.x1 < b.x2 && b.x1 < a.x2 && a.y1 < b.y2 && b.y1 < a.y2; }
  4. Calculate the angle of a line defined by two pointsfunction 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; }
  5. Calculate the distance between two pointsfunction distance({ p1, p2 }) { return Math.hypot(p2.x - p1.x, p2.y - p1.y); }
  6. Calculate the linear interpolation between two numbersfunction lerp({ a, b, amount }) { return (1 - amount) * a + amount * b; }
  7. Normalize the ratio of a number in a rangefunction normalizeRatio({ value, min, max }) { return (value - min) / (max - min); }
  8. Calculate the midpoint between two pointsfunction midpoint({ p1, p2 }) { return [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2]; }
  9. Check if a point is inside a rectanglefunction isInside({ point, rect }) { return point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom; }
  10. Round a number to the nearest multiple of a given valuefunction roundNearest({ value, nearest }) { return Math.round(value / nearest) * nearest; }
  11. Convert radians to degreesfunction radiansToDegrees(radians) { return radians * 180 / Math.PI; }
  12. Calculate the midpoint of a given rangefunction rangeMidpoint([from, to]) { return (from + to) / 2; }
  13. Linear scale a number between rangesfunction linearScale({ value, inMin, inMax, outMin, outMax }) { return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin; }
  14. Linear scale of a number between two rangesfunction scale({ value, from, to }) { return ((value - from[0]) * (to[1] - to[0])) / (from[1] - from[0]) + to[0]; }

Function 17 lines

  1. Logical xor operatorfunction xor([a, b]) { return Boolean(a) !== Boolean(b); }
  2. Identity functionfunction identity(value) { return value; }
  3. Box handlerfunction boxHandler(value) { return { next: f => boxHandler(f(value)), done: f => f(value) }; }
  4. Check if a value is a functionfunction isFunction(value) { return typeof value === 'function'; }
  5. Check if a value is a generator functionfunction isGeneratorFunction(value) { return ['[object GeneratorFunction]', '[object AsyncGeneratorFunction]'].includes(Object.prototype.toString.call(value)); }
  6. Check if a value is an async functionfunction isAsyncFunction(value) { return Object.prototype.toString.call(value) === '[object AsyncFunction]'; }
  7. Compose functions from left to rightfunction pipe(...fns) { return input => fns.reduce((value, fn) => fn(value), input); }
  8. Compose functionsfunction compose(...fns) { return input => fns.reduceRight((value, fn) => fn(value), input); }
  9. Create a function that accepts a single argumentfunction unary(fn) { return value => fn(value); }
  10. Create an empty functionfunction noop() {}
  11. Curry a functionfunction curry(fn, ...args) { return fn.length <= args.length ? fn(...args) : (...more) => curry(fn, ...args, ...more); }
  12. Delay the evaluation of a functionfunction thunkify(fn) { return (...args) => () => fn(...args); }
  13. Execute a function oncefunction once(fn) { let done = false, result; return (...args) => { if (!done) { result = fn(...args); done = true; } return result; }; }
  14. Flip the arguments of a functionfunction flip(fn) { return (...args) => fn(...args.reverse()); }
  15. Memoize a functionfunction memoize(fn) { const cache = new Map(); return arg => { if (!cache.has(arg)) cache.set(arg, fn(arg)); return cache.get(arg); }; }
  16. Partially apply a functionfunction partial(fn, ...preset) { return (...rest) => fn(...preset, ...rest); }
  17. Uncurry a functionfunction uncurry(fn, depth = 1) { return (...args) => args.slice(0, depth).reduce((next, arg) => next(arg), fn); }

Random 17 lines

  1. Generate a random booleanfunction randomBoolean() { return Math.random() < 0.5; }
  2. Generate a random floating point number in given rangefunction randomFloat(min, max) { return Math.random() * (max - min) + min; }
  3. Generate a random hex colorfunction randomColor() { return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0')}`; }
  4. Generate a random integer in given rangefunction randomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
  5. Generate a random IP addressfunction 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}`; }
  6. Generate a random signfunction randomSign() { return Math.random() < 0.5 ? -1 : 1; }
  7. Generate a random string from given charactersfunction 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; }
  8. Generate a random string using Node crypto moduleimport { randomBytes } from 'node:crypto'; function randomToken(bytes = 32) { return randomBytes(bytes).toString('hex'); }
  9. Generate a random string with given lengthfunction randomId(length) { const alphabet = '0123456789abcdefghjkmnpqrstvwxyz'; return Array.from(crypto.getRandomValues(new Uint8Array(length)), byte => alphabet[byte % 32]).join(''); }
  10. Generate a random UUIDfunction uuid() { return crypto.randomUUID(); }
  11. Generate a weighted random number in given rangefunction weightedRandom(min, max) { return Math.floor(Math.random() ** 2 * (max - min)) + min; }
  12. Generate an array of random integers in a given rangefunction randomIntegers(min, max, count) { return Array.from({ length: count }, () => Math.floor(Math.random() * (max - min + 1)) + min); }
  13. Get a random item and remove it from an arrayfunction takeRandomItem(values) { return values.splice(Math.floor(Math.random() * values.length), 1)[0]; }
  14. Get a random item from an arrayfunction randomItem(values) { return values[Math.floor(Math.random() * values.length)]; }
  15. Get random items of an arrayfunction 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); }
  16. Pick a random property of an objectfunction randomKey(object) { const keys = Object.keys(object); return keys[Math.floor(Math.random() * keys.length)]; }
  17. Pick random lines from a text documentfunction 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

  1. Check if a given DOMRect is contained within another DOMRectfunction 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; }
  2. Check if two DOMRects intersectfunction 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; }
  3. Compare two DOMRects for size and position matchfunction sameRect({ a, b }) { return ['x', 'y', 'width', 'height'].every(key => a[key] === b[key]); }
  4. Get the center point of a DOMRectfunction getCenter({ x, y, width, height }) { return [x + width / 2, y + height / 2]; }
  5. Calculate the distance to the bottom of a pagefunction distanceToBottom() { return document.documentElement.scrollHeight - window.innerHeight - window.scrollY; }
  6. Check if an element has CSS overflowfunction hasCssOverflow(element) { const { overflowX, overflowY } = getComputedStyle(element); return [overflowX, overflowY].some(value => ['auto', 'scroll'].includes(value)); }
  7. Check if an element has overflowfunction hasOverflow(element) { return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth; }
  8. Check if an element is a descendant of anotherfunction isDescendant(child, parent) { return child !== parent && parent.contains(child); }
  9. Check if an element is focusedfunction hasFocus(element) { return element === document.activeElement; }
  10. Check if the touch events are supportedfunction touchSupported() { return 'ontouchstart' in window || navigator.maxTouchPoints > 0; }
  11. Check if user scrolls to the bottom of the pagefunction isAtBottom(tolerance = 1) { const { scrollHeight, clientHeight } = document.documentElement; return scrollHeight - clientHeight - window.scrollY <= tolerance; }
  12. Detect Internet Explorer browserfunction isInternetExplorer() { return 'documentMode' in document; }
  13. Detect macOS browserfunction isApplePlatform() { return /Mac|iPhone|iPad|iPod/.test(navigator.userAgentData?.platform ?? navigator.platform); }
  14. Get all siblings of an elementfunction siblings(element) { return element.parentElement ? [...element.parentElement.children].filter(child => child !== element) : []; }
  15. Get the position of an element relative to the documentfunction getPosition(element) { const rect = element.getBoundingClientRect(); return { left: rect.left + window.scrollX, top: rect.top + window.scrollY }; }
  16. Get the selected textfunction getSelectedText() { return window.getSelection()?.toString() ?? ''; }
  17. Go back to the previous pagefunction goBack() { history.back(); }
  18. Hide an elementfunction hide(element) { element.hidden = true; }
  19. Insert an element after other onefunction insertAfter(element, reference) { reference.after(element); }
  20. Insert an element before other onefunction insertBefore(element, reference) { reference.before(element); }
  21. Insert given HTML after an elementfunction insertHtmlAfter(html, element) { element.insertAdjacentHTML('afterend', html); }
  22. Insert given HTML before an elementfunction insertHtmlBefore(html, element) { element.insertAdjacentHTML('beforebegin', html); }
  23. Redirect to another pagefunction goTo(url) { location.assign(url); }
  24. Reload the current pagefunction reload() { location.reload(); }
  25. Replace an elementfunction replace(element, replacement) { element.replaceWith(replacement); }
  26. Scroll to top of the pagefunction goToTop() { window.scrollTo(0, 0); }
  27. Serialize form datafunction 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]])); }
  28. Show an elementfunction show(element) { element.hidden = false; element.style.removeProperty('display'); }
  29. Strip HTML from a given textfunction stripHtml(html) { return new DOMParser().parseFromString(html, 'text/html').body.textContent ?? ''; }
  30. Toggle an elementfunction toggle(element) { element.hidden = !element.hidden; }

Misc 28 lines

  1. Convert Celsius to Fahrenheitfunction toFahrenheit(value) { return value * 9 / 5 + 32; }
  2. Convert hex to RGBfunction 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)); }
  3. Convert URL parameters to objectfunction 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 }), {}); }
  4. Convert 3 digits color to 6 digits colorfunction toFullHexColor(color) { return `#${(color.startsWith('#') ? color.slice(1) : color).split('').map(digit => `${digit}${digit}`).join('')}`; }
  5. Convert Fahrenheit to Celsiusfunction fahrenheitToCelsius(fahrenheit) { return (fahrenheit - 32) * 5 / 9; }
  6. Get the value of a param from a URLfunction getParam({ url, param }) { return new URL(url).searchParams.get(param); }
  7. Convert RGB color to hexfunction rgbToHex({ red, green, blue }) { return `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`; }
  8. Convert cookie to objectfunction 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()])); }
  9. Easing functionsfunction 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]; }
  10. Encode a URL component strictlyfunction encodeStrict(value) { return encodeURIComponent(value).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`); }
  11. Get the value of a cookiefunction getCookie({ cookie, name }) { const match = `; ${cookie}`.split(`; ${name}=`); return match.length > 1 ? match.pop().split(';').shift() : null; }
  12. Get the type of a variable as a stringfunction getTypeOf(value) { return Object.prototype.toString.call(value).match(/\[object (.*)\]/)[1]; }
  13. Swap two variablesfunction swap([a, b]) { [a, b] = [b, a]; return [a, b]; }
  14. Decode a JWT tokenfunction 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(''))); }
  15. Get the first defined and non-null valuefunction coalesce(values) { return values.find(item => item !== undefined && item !== null) ?? null; }
  16. Convert a Lab color to an LCH colorfunction labToLch([l, a, b]) { return [l, Math.hypot(a, b), ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360]; }
  17. Convert an LCH color to a Lab colorfunction lchToLab([l, c, h]) { return [l, Math.cos((h * Math.PI) / 180) * c, Math.sin((h * Math.PI) / 180) * c]; }
  18. Check if the code is running in Jestfunction isRunningInJest() { return typeof process !== 'undefined' && process.env.JEST_WORKER_ID !== undefined; }
  19. Check if the code is running in NodeJSfunction isNode() { return typeof process !== 'undefined' && process.versions?.node != null; }
  20. Check if the code is running in the browserfunction isBrowser() { return typeof window === 'object' && typeof document === 'object'; }
  21. Clear all cookiesfunction clearCookies() { for (const cookie of document.cookie.split(';')) { const name = cookie.split('=')[0].trim(); if (name) document.cookie = `${name}=; Max-Age=0; path=/`; } }
  22. Detect dark modefunction isDarkMode() { return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false; }
  23. Emulate a dice throwfunction throwDice() { return Math.floor(Math.random() * 6) + 1; }
  24. Generate an unique and increment idfunction createIdGenerator(start = 0) { let id = start; return () => id++; }
  25. Redirect the page to HTTPS if it is in HTTPfunction redirectToHttps() { if (location.protocol !== 'http:') return; const url = new URL(location.href); url.protocol = 'https:'; location.replace(url); }
  26. Run Promises in sequenceasync function runInSequence(tasks) { const results = []; for (const task of tasks) results.push(await task()); return results; }
  27. Wait for an amount of timefunction wait(milliseconds) { return new Promise(resolve => setTimeout(resolve, milliseconds)); }
  28. Wait for the next event loopfunction nextTask() { return new Promise(resolve => setTimeout(resolve, 0)); }

Email 10 lines

  1. Convert an email domain to punycodeby Oveyonfunction toAsciiAddress(address) { const at = address.lastIndexOf('@'); return `${address.slice(0, at)}@${new URL(`http://${address.slice(at + 1)}`).hostname}`; }
  2. Get the domain of an email addressby Oveyonfunction emailDomain(address) { return address.slice(address.lastIndexOf('@') + 1).toLowerCase(); }
  3. Mask an email address for logsby Oveyonfunction maskEmail(address) { return `${address.slice(0, 1)}•••${address.slice(address.lastIndexOf('@'))}`; }
  4. Normalize an email address for comparisonby Oveyonfunction normalizeEmail(address) { const value = address.trim(); const at = value.lastIndexOf('@'); return `${value.slice(0, at)}@${value.slice(at + 1).toLowerCase()}`; }
  5. Read a Retry-After headerby Oveyonfunction retryAfterMs({ retryAfter, date }) { const seconds = Number(retryAfter); return Math.max(0, Number.isFinite(seconds) ? seconds * 1000 : Date.parse(retryAfter) - Date.parse(date)); }
  6. Compute a backoff delay with full jitterby Oveyonfunction backoffMs({ attempt, baseMs, capMs, random }) { return Math.round(random * Math.min(capMs, baseMs * 2 ** attempt)); }
  7. Build an idempotency key from an eventby Oveyonfunction idempotencyKey({ scope, id, version }) { return [scope, id, version].map(part => encodeURIComponent(String(part))).join(':'); }
  8. Classify an SMTP replyby Oveyonfunction 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' }; }
  9. Build a DMARC recordby Oveyonfunction dmarcRecord({ policy, rua }) { return ['v=DMARC1', `p=${policy}`, ...(rua ? [`rua=${rua}`] : [])].join('; '); }
  10. Parse a DMARC recordby Oveyonfunction 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.

Type two or more characters. Try “duplicate”, “webhook” or “retry”.