# The one-line sheet

Every curated JavaScript utility on 1loc.dev as the exact function the lab or the tests run, grouped by topic.

Canonical: https://1loc.dev/library/cheatsheet/
Maintained by Oveyon. Updated 2026-10-28.

## array

### Clone an array

Create a new array without copying the objects inside it. https://1loc.dev/array/clone-an-array/

```javascript
function clone(values) { return [...values]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This is a shallow copy: nested objects keep the same identity.

### Remove duplicate values

Keep the first occurrence of each value, in its original order. https://1loc.dev/array/remove-duplicate-values-in-an-array/

```javascript
function unique(values) { return [...new Set(values)]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Set compares objects by reference. Two separately created objects are not duplicates.

### Flatten a nested array

Turn a nested array into one sequence of values. https://1loc.dev/array/flatten-an-array/

```javascript
function flatten(values) { return values.flat(Infinity); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input depth is capped at 12 and the total element count at 1,000 in this lab.

### Split an array into chunks

Build consecutive chunks without changing the original array. https://1loc.dev/array/split-an-array-into-chunks/

```javascript
function chunk({ values, size }) { return Array.from({ length: Math.ceil(values.length / size) }, (_, i) => values.slice(i * size, (i + 1) * size)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Size must be an integer from 1 to 1,000; zero is rejected before allocation.

### Find the intersection of arrays

Return the distinct values that occur in both arrays. https://1loc.dev/array/get-the-intersection-of-arrays/

```javascript
function intersection({ left, right }) { const other = new Set(right); return [...new Set(left)].filter(value => other.has(value)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Result order follows the first array. Duplicate results are removed.

### Sort numbers in ascending order

Sort a numeric copy instead of using JavaScript’s default string ordering. https://1loc.dev/array/sort-an-array-of-numbers/

```javascript
function sortNumbers(values) { return [...values].sort((a, b) => a - b); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab accepts finite numbers only. The source array remains unchanged.

### Sum an array of numbers

Add numeric values with an explicit result for an empty array. https://1loc.dev/array/get-the-sum-of-an-array-of-numbers/

```javascript
function sum(values) { return values.reduce((total, value) => total + value, 0); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Floating-point arithmetic is approximate; use integer minor units or a decimal library for money.

### Group objects by a key

Collect records by a string or numeric field without prototype-key collisions. https://1loc.dev/array/group-an-array-of-objects-by-a-key/

```javascript
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); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Every record must own the grouping field, with a string or number value.

### Cast a value as an array

Wrap a single value in an array and return arrays unchanged. https://1loc.dev/array/cast-a-value-as-an-array/

```javascript
function castArray(value) { return Array.isArray(value) ? value : [value]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Arrays are returned as they are, not copied.

### Convert an array of strings to numbers

Map every string with Number. https://1loc.dev/array/convert-an-array-of-strings-to-numbers/

```javascript
function toNumbers(values) { return values.map(Number); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Number("") is 0 and surrounding spaces are ignored, as the edge case shows. Invalid strings become NaN (null in JSON) — validate user input first.

### Get all subsets of an array

Build the power set, smallest subsets first. https://1loc.dev/array/get-all-subsets-of-an-array/

```javascript
function getSubsets(values) { return values.reduce((subsets, value) => subsets.concat(subsets.map(subset => [...subset, value])), [[]]); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The result has 2^n subsets, so the lab accepts at most 10 values (1,024 subsets).

### Get union of arrays

Merge arrays and keep each value once, in first-seen order. https://1loc.dev/array/get-union-of-arrays/

```javascript
function union(arrays) { return [...new Set(arrays.flat())]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original took the arrays as separate arguments; the lab passes one array of arrays.

### Swap the rows and columns of a matrix

Transpose a rectangular matrix. https://1loc.dev/array/swap-the-rows-and-columns-of-a-matrix/

```javascript
function transpose(matrix) { return matrix[0].map((_, column) => matrix.map(row => row[column])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Rows must have the same length; the lab requires a non-empty rectangular matrix.

### Swap two array items

Return a copy with the items at i and j exchanged. https://1loc.dev/array/swap-two-array-items/

```javascript
function swapItems({ values, i, j }) { const copy = [...values]; [copy[i], copy[j]] = [copy[j], copy[i]]; return copy; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original only swapped when both items were truthy, so arrays containing 0 or "" were returned unchanged. Destructuring swaps any values and works in either index order.

### Unzip an array of arrays

Regroup the n-th item of every array into the n-th output array. https://1loc.dev/array/unzip-an-array-of-arrays/

```javascript
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])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Shorter arrays simply contribute fewer items.

### Compare two arrays

Check the same length and the same items in the same order. https://1loc.dev/array/compare-two-arrays/

```javascript
function isEqual({ a, b }) { return a.length === b.length && a.every((value, i) => Object.is(value, b[i])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Shallow comparison with Object.is. The original JSON.stringify variant treats undefined and null alike and depends on key order for nested objects.

### Convert an array of objects to a single object

Index records by a key field. https://1loc.dev/array/convert-an-array-of-objects-to-a-single-object/

```javascript
function toObject({ values, key }) { return Object.fromEntries(values.map(item => [item[key], item])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A repeated key keeps the last record, as the edge case shows.

### Count the occurrences of a value in an array

Count items strictly equal to a value. https://1loc.dev/array/count-the-occurrences-of-a-value-in-an-array/

```javascript
function countOccurrences({ values, value }) { return values.filter(item => item === value).length; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Strict equality: 1 and "1" differ.

### Count the occurrences of array elements

Tally every distinct value into an object. https://1loc.dev/array/count-the-occurrences-of-array-elements/

```javascript
function countEach(values) { return { ...values.reduce((counts, value) => ((counts[value] = (counts[value] || 0) + 1), counts), Object.create(null)) }; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Keys become strings, so 1 and "1" share a count.

### Create an array of numbers in the given range

List the integers from min to max inclusive. https://1loc.dev/array/create-an-array-of-numbers-in-the-given-range/

```javascript
function range({ min, max }) { return Array.from({ length: max - min + 1 }, (_, i) => min + i); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab requires min ≤ max and at most 1,000 numbers before allocating.

### Create cartesian product

Combine one item from each set in every possible way. https://1loc.dev/array/create-cartesian-product/

```javascript
function cartesian(sets) { return sets.reduce((product, set) => product.flatMap(prefix => set.map(item => [...prefix, item])), [[]]); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The result size is the product of the set sizes; the lab caps it at 1,000 combinations.

### Find the minimum item of an array

Spread the numbers into Math.min. https://1loc.dev/array/find-the-minimum-item-of-an-array/

```javascript
function min(values) { return Math.min(...values); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns Infinity (null in JSON); check the length first. Spreading very large arrays can exceed the argument limit; reduce instead.

### Get the rank of an array of numbers

Rank each number by how many values are larger, starting at 1. https://1loc.dev/array/get-the-rank-of-an-array-of-numbers/

```javascript
function ranking(values) { return values.map(value => values.filter(other => other > value).length + 1); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Ties share a rank and the next rank is skipped (competition ranking).

### Remove falsy values from array

Filter with Boolean. https://1loc.dev/array/remove-falsy-values-from-array/

```javascript
function removeFalsy(values) { return values.filter(Boolean); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). 0 and "" are falsy too — filter explicitly when they are valid values.

### Zip multiple arrays

Pair the n-th items of several arrays. https://1loc.dev/array/zip-multiple-arrays/

```javascript
function zip(arrays) { return Array.from({ length: Math.max(0, ...arrays.map(array => array.length)) }, (_, i) => arrays.map(array => array[i] ?? null)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Missing items become null (undefined in the original) so the result is JSON-representable.

### Compare two arrays regardless of order

Compare the sorted sets of distinct values. https://1loc.dev/array/compare-two-arrays-regardless-of-order/

```javascript
function isEqualIgnoringOrder({ a, b }) { const normalize = values => JSON.stringify([...new Set(values)].sort()); return normalize(a) === normalize(b); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Duplicates are ignored, as the edge case shows; compare counts when multiplicity matters.

### Count by the properties of an array of objects

Tally records by the value of one field. https://1loc.dev/array/count-by-the-properties-of-an-array-of-objects/

```javascript
function countBy({ values, key }) { return { ...values.reduce((counts, item) => ((counts[item[key]] = (counts[item[key]] || 0) + 1), counts), Object.create(null)) }; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Records without the field are counted under "undefined".

### Create an array of cumulative sum

Replace each number with the running total up to it. https://1loc.dev/array/create-an-array-of-cumulative-sum/

```javascript
function accumulate(values) { let total = 0; return values.map(value => (total += value)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Floating-point totals can drift; sum integer minor units for money.

### Find the index of the maximum item of an array

Return the index of the first largest number. https://1loc.dev/array/find-the-index-of-the-maximum-item-of-an-array/

```javascript
function indexOfMax(values) { return values.reduce((best, value, i) => (value > values[best] ? i : best), 0); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The first maximum wins on ties. An empty array returns 0, as in the original — check the length first.

### Find the maximum item of an array by given key

Return the record with the largest value in a field. https://1loc.dev/array/find-the-maximum-item-of-an-array-by-given-key/

```javascript
function maxBy({ values, key }) { return values.reduce((best, item) => (best === null || item[key] > best[key] ? item : best), null); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns null; the original returned {}.

### Find the maximum item of an array

Spread the numbers into Math.max. https://1loc.dev/array/find-the-maximum-item-of-an-array/

```javascript
function max(values) { return Math.max(...values); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns -Infinity (null in JSON); check the length first.

### Generate an array of alphabet characters

List the first count lowercase ASCII letters. https://1loc.dev/array/generate-an-array-of-alphabet-characters/

```javascript
function alphabet(count) { return Array.from({ length: count }, (_, i) => String.fromCharCode(97 + i)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original produced all 26 letters as a constant; a count input makes it runnable here.

### Get all arrays of consecutive elements

Slide a window of a given size across an array. https://1loc.dev/array/get-all-arrays-of-consecutive-elements/

```javascript
function windows({ values, size }) { return size > values.length ? [] : values.slice(size - 1).map((_, i) => values.slice(i, i + size)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A window larger than the array yields no windows.

### Get indices of a value in an array

Collect every index where a value appears. https://1loc.dev/array/get-indices-of-a-value-in-an-array/

```javascript
function indices({ values, value }) { return values.flatMap((item, i) => (item === value ? [i] : [])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original second variant dropped index 0, because filter(Boolean) removes it; flatMap keeps it.

### Get the average of an array

Divide the sum by the count. https://1loc.dev/array/get-the-average-of-an-array/

```javascript
function average(values) { return values.reduce((sum, value) => sum + value, 0) / values.length; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Floating-point sums are approximate, as the edge case shows.

### Get the unique values of an array

Keep the first occurrence of each value with a Set. https://1loc.dev/array/get-the-unique-values-of-an-array/

```javascript
function uniqueValues(values) { return [...new Set(values)]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Same idea as Remove duplicate values; SameValueZero treats NaN as equal to NaN.

### Intersperse element between elements

Insert a separator between every pair of items. https://1loc.dev/array/intersperse-element-between-elements/

```javascript
function intersperse({ values, separator }) { return values.flatMap((value, i) => (i === 0 ? [value] : [separator, value])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original built Array(2n − 1), which throws for an empty array; flatMap returns [].

### Sort an array of items by given key

Return a copy sorted by one field, ascending. https://1loc.dev/array/sort-an-array-of-items-by-given-key/

```javascript
function sortBy({ values, key }) { return [...values].sort((a, b) => (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Mixed types compare unpredictably; keep the field one type.

### Check if an array is empty

Return true for an array without items. https://1loc.dev/array/check-if-an-array-is-empty/

```javascript
function isEmptyArray(value) { return Array.isArray(value) && !value.length; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Non-arrays return false rather than throwing.

### Find the closest number from an array

Return the item nearest to a target. https://1loc.dev/array/find-the-closest-number-from-an-array/

```javascript
function closest({ values, target }) { return values.reduce((best, value) => (Math.abs(value - target) < Math.abs(best - target) ? value : best)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The first candidate wins on ties, as the edge case shows. The lab requires at least one number.

### Find the index of the minimum item of an array

Return the index of the first smallest number. https://1loc.dev/array/find-the-index-of-the-minimum-item-of-an-array/

```javascript
function indexOfMin(values) { return values.reduce((best, value, i) => (value < values[best] ? i : best), 0); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The first minimum wins on ties. An empty array returns 0 — check the length first.

### Find the length of the longest string in an array

Map strings to lengths and take the maximum. https://1loc.dev/array/find-the-length-of-the-longest-string-in-an-array/

```javascript
function longestLength(words) { return Math.max(0, ...words.map(word => word.length)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Starting from 0 makes an empty array return 0; the original returned -Infinity.

### Find the minimum item of an array by given key

Return the record with the smallest value in a field. https://1loc.dev/array/find-the-minimum-item-of-an-array-by-given-key/

```javascript
function minBy({ values, key }) { return values.reduce((best, item) => (best === null || item[key] < best[key] ? item : best), null); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns null; the original returned {}.

### Get all nth items of an array

Keep every nth item, starting with the nth. https://1loc.dev/array/get-all-nth-items-of-an-array/

```javascript
function getNthItems({ values, nth }) { return values.filter((_, i) => i % nth === nth - 1); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). nth must be a positive integer.

### Merge two arrays

Concatenate two arrays, optionally dropping duplicates. https://1loc.dev/array/merge-two-arrays/

```javascript
function merge({ a, b, unique = false }) { return unique ? [...new Set([...a, ...b])] : [...a, ...b]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original page showed both versions; unique selects one.

### Repeat an array

Concatenate an array with itself n times. https://1loc.dev/array/repeat-an-array/

```javascript
function repeatArray({ values, times }) { return Array(times).fill(values).flat(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). flat() flattens one level only, so nested arrays inside values stay nested.

### Empty an array

Remove every item in place, so all references see an empty array. https://1loc.dev/array/empty-an-array/

```javascript
function empty(values) { values.length = 0; return values; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Setting length mutates the array. Assigning [] only rebinds one variable, as the second example shows.

### Find the index of the last matching item of an array

Scan from the end and return the first index whose item matches. https://1loc.dev/array/find-the-index-of-the-last-matching-item-of-an-array/

```javascript
function lastIndex(values, predicate) { return values.findLastIndex(predicate); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Array.prototype.findLastIndex is ES2023: Node.js 18+ and current browsers. The original reduced the whole array; findLastIndex stops at the first match from the end.

### Partition an array based on a condition

Split items into [matching, not matching] in one pass. https://1loc.dev/array/partition-an-array-based-on-a-condition/

```javascript
function partition(values, predicate) { return values.reduce((groups, value) => (groups[predicate(value) ? 0 : 1].push(value), groups), [[], []]); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The predicate’s result is tested for truthiness: n % 2 puts odd numbers first.

### Shuffle an array

Return a new array in random order, every order equally likely. https://1loc.dev/array/shuffle-an-array/

```javascript
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;
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Fisher–Yates in O(n). The original sorted by random keys, which is also unbiased but O(n log n); avoid sort(() => Math.random() - 0.5), which is biased.

## validator

### Check whether all values are equal

Compare every item with the first using Object.is. https://1loc.dev/validator/check-if-all-items-in-an-array-are-equal/

```javascript
function allEqual(values) { return values.every(value => Object.is(value, values[0])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The empty array returns true: no item violates the condition.

### Check whether an object is empty

Check for own enumerable string keys on a JSON object. https://1loc.dev/validator/check-if-an-object-is-empty/

```javascript
function isEmpty(value) { return Object.keys(value).length === 0; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input must be a non-null object, not an array. Symbol and non-enumerable keys are outside this JSON contract.

### Check whether an integer is even

Test parity for safe integers, including zero and negative values. https://1loc.dev/validator/check-if-a-number-is-even/

```javascript
function isEven(value) { return value % 2 === 0; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The input must be a safe integer. Fractional values are rejected.

### Check a leap year

Apply the Gregorian divisible-by-4, century and 400-year rules. https://1loc.dev/validator/check-if-a-year-is-leap-year/

```javascript
function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input is an integer year from 1 to 9,999 in the proleptic Gregorian calendar.

### Check if a character is a digit

Test that a string is exactly one ASCII digit from 0 to 9. https://1loc.dev/validator/check-if-a-character-is-a-digit/

```javascript
function isDigit(char) { return /^[0-9]$/.test(char); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original `char < 10` accepted "", " " and "-1" because of numeric coercion, and one variant referenced an undefined variable. This version tests exactly one ASCII digit.

### Check if a date is a weekend

Return true when a YYYY-MM-DD date falls on a Saturday or Sunday. https://1loc.dev/validator/check-if-a-date-is-a-weekend/

```javascript
function isWeekend(date) { return new Date(date).getUTCDay() % 6 === 0; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The date is read as a UTC calendar day, so the result does not depend on the machine’s time zone. The original used local time on a Date object.

### Check if a flat array has duplicate values

Compare the size of a Set with the array length. https://1loc.dev/validator/check-if-a-flat-array-has-duplicate-values/

```javascript
function hasDuplicates(values) { return new Set(values).size !== values.length; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values use SameValueZero: NaN equals NaN, and objects compare by reference.

### Check if a date is between two dates

Test whether a YYYY-MM-DD date falls inside an inclusive range. https://1loc.dev/validator/check-if-a-date-is-between-two-dates/

```javascript
function isBetween({ date, min, max }) { const time = Date.parse(date); return time >= Date.parse(min) && time <= Date.parse(max); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Both ends are included. Dates are UTC calendar days, so the machine’s time zone does not matter.

### Check if a date is today

Compare the UTC calendar day of a date-time with the current one. https://1loc.dev/validator/check-if-a-date-is-today/

```javascript
function isToday({ dateTime, now }) { return new Date(dateTime).toISOString().slice(0, 10) === new Date(now).toISOString().slice(0, 10); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). now is an input so the result is testable; pass new Date().toISOString() in your code.

### Check if a date occurs in the current year

Compare the UTC year of a date-time with the current one. https://1loc.dev/validator/check-if-a-date-occurs-in-the-current-year/

```javascript
function isCurrentYear({ dateTime, now }) { return new Date(dateTime).getUTCFullYear() === new Date(now).getUTCFullYear(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The year is the UTC year: New Year’s Eve at 23:00 in São Paulo is already 2026 in UTC, as the edge case shows.

### Check if a given integer is a prime number

Trial division up to the square root, without allocating an array. https://1loc.dev/validator/check-if-a-given-integer-is-a-prime-number/

```javascript
function isPrime(n) { if (n < 2) return false; for (let i = 2; i * i <= n; i++) if (n % i === 0) return false; return true; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original built an array of candidates; a loop stops at the first divisor and allocates nothing.

### Check if a number is positive

Return true for numbers greater than zero. https://1loc.dev/validator/check-if-a-number-is-positive/

```javascript
function isPositive(n) { return Math.sign(n) === 1; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Zero is neither positive nor negative.

### Check if a string contains upper case characters

Compare a string with its lowercase form. https://1loc.dev/validator/check-if-a-string-contains-upper-case-characters/

```javascript
function containsUpperCase(text) { return text !== text.toLowerCase(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Any cased letter counts, in any script. Digits and symbols never do.

### Check if a date is a weekday

Return true for a YYYY-MM-DD date from Monday to Friday. https://1loc.dev/validator/check-if-a-date-is-a-weekday/

```javascript
function isWeekday(date) { return new Date(date).getUTCDay() % 6 !== 0; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Reads the UTC calendar day; the original used local time on a Date object. Public holidays are not considered.

### Check if a number is a power of 2

Use the bit trick n & (n − 1) on a positive integer. https://1loc.dev/validator/check-if-a-number-is-a-power-of-2/

```javascript
function isPowerOfTwo(n) { return n > 0 && (n & (n - 1)) === 0; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original returned true for 0; this version requires n > 0.

### Check if a number is negative

Return true for numbers below zero. https://1loc.dev/validator/check-if-a-number-is-negative/

```javascript
function isNegative(n) { return n < 0; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). -0 is not negative here, matching n < 0.

### Check if a string contains only letters and numbers

Test for one or more ASCII letters or digits. https://1loc.dev/validator/check-if-a-string-contains-only-letters-and-numbers/

```javascript
function isAlphanumeric(text) { return /^[0-9A-Z]+$/i.test(text); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). ASCII only: accented letters and spaces fail. The empty string fails too.

### Check if a string is a MongoDB ObjectId

Test for exactly 24 hexadecimal characters. https://1loc.dev/validator/check-if-a-string-is-a-mongo-db-object-id/

```javascript
function isMongoId(text) { return /^[0-9a-f]{24}$/i.test(text); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This checks the format only, not that the document exists.

### Check if a string is upper case

Compare a string with its uppercase form. https://1loc.dev/validator/check-if-a-string-is-upper-case/

```javascript
function isUpperCase(text) { return text === text.toUpperCase(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A string without letters is unchanged by toUpperCase, so it counts as upper case, as the edge case shows.

### Check if all array elements are equal to a given value

Compare every item with a value using ===. https://1loc.dev/validator/check-if-all-array-elements-are-equal-to-a-given-value/

```javascript
function isEqual({ values, value }) { return values.every(item => item === value); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns true: no item differs.

### Check if a number is in a given range

Test an inclusive range whose ends may be given in any order, with an optional tolerance. https://1loc.dev/validator/check-if-a-number-is-in-a-given-range/

```javascript
function inRange({ value, a, b, threshold = 0 }) { return Math.min(a, b) - threshold <= value && value <= Math.max(a, b) + threshold; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Both ends are included; threshold widens the range on both sides.

### Check if a number is odd

Test that an integer leaves a remainder when divided by 2. https://1loc.dev/validator/check-if-a-number-is-odd/

```javascript
function isOdd(n) { return n % 2 !== 0; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Comparing with !== 0 handles negatives: -3 % 2 is -1.

### Check if a string contains lower case characters

Compare a string with its uppercase form. https://1loc.dev/validator/check-if-a-string-contains-lower-case-characters/

```javascript
function containsLowerCase(text) { return text !== text.toUpperCase(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Any cased letter counts, in any script.

### Check if a string contains only ASCII characters

Test that every character is in the 0–127 range. https://1loc.dev/validator/check-if-a-string-contains-only-ascii-characters/

```javascript
function isAscii(text) { return /^[\x00-\x7F]+$/.test(text); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The empty string fails.

### Check if a string contains only digits

Test for one or more ASCII digits. https://1loc.dev/validator/check-if-a-string-contains-only-digits/

```javascript
function isNumeric(text) { return /^[0-9]+$/.test(text); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original returned true for the empty string; this version requires at least one digit.

### Check if a string contains only letters

Test for one or more ASCII letters. https://1loc.dev/validator/check-if-a-string-contains-only-letters/

```javascript
function isAlpha(text) { return /^[A-Z]+$/i.test(text); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). ASCII only: use /^\p{L}+$/u for letters in any script.

### Check if a string is a hexadecimal color

Accept #rgb, #rgba, #rrggbb and #rrggbbaa. https://1loc.dev/validator/check-if-a-string-is-a-hexadecimal-color/

```javascript
function isHexColor(color) { return /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Named colors, rgb() and hsl() are not hexadecimal.

### Check if a string is a hexadecimal number

Test for one or more hexadecimal digits. https://1loc.dev/validator/check-if-a-string-is-a-hexadecimal-number/

```javascript
function isHexadecimal(text) { return /^[0-9a-f]+$/i.test(text); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A 0x prefix fails, as the edge case shows; strip it first.

### Check if a string is an octal number

Test for octal digits with an optional 0o prefix. https://1loc.dev/validator/check-if-a-string-is-an-octal-number/

```javascript
function isOctal(text) { return /^(0o)?[0-7]+$/i.test(text); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Legacy leading-zero octal such as 0755 passes as plain digits.

### Check if a string is lower case

Compare a string with its lowercase form. https://1loc.dev/validator/check-if-a-string-is-lower-case/

```javascript
function isLowerCase(text) { return text === text.toLowerCase(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A string without letters counts as lower case.

### Check if a value is a business identifier code

Test the shape of an 8- or 11-character BIC (SWIFT) code. https://1loc.dev/validator/check-if-a-value-is-a-business-identifier-code/

```javascript
function isBic(value) { return /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This checks the ISO 9362 format only — not that the institution or country code exists.

### Check if a value is a plain object

Return true for objects whose prototype is Object.prototype or null. https://1loc.dev/validator/check-if-a-value-is-a-plain-object/

```javascript
function isPlainObject(value) { return value !== null && typeof value === 'object' && [null, Object.prototype].includes(Object.getPrototypeOf(value)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Uses Object.getPrototypeOf instead of the __proto__ accessor, which an own "__proto__" key can shadow.

### Check if a value is a string

Use Object.prototype.toString so String objects count too. https://1loc.dev/validator/check-if-a-value-is-a-string/

```javascript
function isString(value) { return Object.prototype.toString.call(value) === '[object String]'; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). typeof value === "string" is enough unless you must accept new String() objects.

### Check if a value is base32 encoded

Test the RFC 4648 base32 alphabet and a length that is a multiple of 8. https://1loc.dev/validator/check-if-a-value-is-base32-encoded/

```javascript
function isBase32(value) { return value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Uppercase alphabet only; the amount of padding is not verified.

### Check if a value is base58 encoded

Test the Bitcoin base58 alphabet, which leaves out 0, O, I and l. https://1loc.dev/validator/check-if-a-value-is-base58-encoded/

```javascript
function isBase58(value) { return /^[A-HJ-NP-Za-km-z1-9]*$/.test(value); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The empty string passes; checksums such as Base58Check are not verified.

### Check if a value is nil

Return true for null and undefined. https://1loc.dev/validator/check-if-a-value-is-nil/

```javascript
function isNil(value) { return value == null; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). == null is the one loose comparison worth keeping: it matches exactly null and undefined. JSON cannot express undefined.

### Check if an array is not empty

Return true for an array with at least one item. https://1loc.dev/validator/check-if-an-array-is-not-empty/

```javascript
function isNotEmpty(value) { return Array.isArray(value) && value.length > 0; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Uses length rather than Object.keys; the two differ only for sparse arrays, which JSON cannot express.

### Check if an array is a subset of another array

Return true when every value of subset appears in of. https://1loc.dev/validator/check-if-an-array-is-subset-of-other-array/

```javascript
function isSubset({ subset, of }) { const all = new Set(of); return subset.every(value => all.has(value)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original comment said “b is a subset of a” while its code tested the opposite, and its second variant compared joined strings. Named fields remove the ambiguity.

### Validate a Gregorian date

Check that a year, a 1-based month and a day form a real calendar date. https://1loc.dev/validator/validate-a-gregorian-date/

```javascript
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]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original used a zero-based month with new Date(y, m, 0), which reads the previous month’s length and accepted February 30. This version uses a 1-based month and explicit Gregorian rules.

### Check if a string contains whitespace

Test for any whitespace character. https://1loc.dev/validator/check-if-a-string-contains-whitespace/

```javascript
function containsWhitespace(text) { return /\s/.test(text); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original returned a function — which is always truthy — instead of a boolean. This version returns the test result.

### Check if a value is a number

Accept finite numbers and numeric strings. https://1loc.dev/validator/check-if-a-value-is-a-number/

```javascript
function isNumber(value) { return !isNaN(parseFloat(value)) && isFinite(value); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Numeric strings pass on purpose. For numbers only, use Number.isFinite(value).

### Check if a value is an object

Return true for any non-null object, including arrays. https://1loc.dev/validator/check-if-a-value-is-an-object/

```javascript
function isObject(value) { return value !== null && typeof value === 'object'; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Arrays are objects here; use the plain-object check to exclude them.

### Check if a value is base64 encoded

Test standard, padded base64. https://1loc.dev/validator/check-if-a-value-is-base64-encoded/

```javascript
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); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Unpadded and URL-safe (- _) variants fail. Oveyon expects standard base64 for attachment content.

### Check if an object is an array

Use Array.isArray, which works across realms. https://1loc.dev/validator/check-if-an-object-is-an-array/

```javascript
function isArray(value) { return Array.isArray(value); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Prefer Array.isArray to instanceof Array, which fails for arrays from another frame.

### Check if a value is a regular expression

Read the internal tag, which also works for values from another realm. https://1loc.dev/validator/check-if-a-value-is-a-regular-expression/

```javascript
function isRegExp(value) { return Object.prototype.toString.call(value) === '[object RegExp]'; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Works across realms (iframes, vm contexts), where instanceof RegExp fails. Symbol.toStringTag can spoof the tag.

### Check if an array contains a value matching some criterias

True when at least one item satisfies the predicate. https://1loc.dev/validator/check-if-an-array-contains-a-value-matching-some-criterias/

```javascript
function contains(values, predicate) { return values.some(predicate); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). some stops at the first match and returns false for an empty array, as the last line shows.

### Check if an object is a Promise

Detect a thenable: an object or function with a then method. https://1loc.dev/validator/check-if-an-object-is-a-promise/

```javascript
function isPromise(value) { return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function'; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This detects thenables, which is what await and Promise.resolve accept; a plain object with then counts, as the second line shows.

## object

### Pick properties from an object

Build a new object with only the requested own properties. https://1loc.dev/object/pick-a-subset-of-properties-of-an-object/

```javascript
function pick({ value, keys }) { return Object.fromEntries(keys.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Missing and inherited properties are skipped. Values are not deeply cloned.

### Omit properties from an object

Keep the own enumerable fields that are not in a supplied list. https://1loc.dev/object/omit-a-subset-of-properties-from-an-object/

```javascript
function omit({ value, keys }) { return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key))); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This copies enumerable string-keyed properties only. Values remain shared.

### Create an object from pairs of key and value

Turn [key, value] pairs into a plain object with Object.fromEntries. https://1loc.dev/object/create-an-object-from-the-pairs-of-key-and-value/

```javascript
function toObject(pairs) { return Object.fromEntries(pairs); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). When a key repeats, the later pair wins, as the edge case shows.

### Check if multiple objects are equal

Compare JSON serializations with the first object. https://1loc.dev/object/check-if-multiple-objects-are-equal/

```javascript
function areEqual(objects) { return objects.every(object => JSON.stringify(object) === JSON.stringify(objects[0])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Key order matters to JSON.stringify, as the edge case shows; undefined values and functions are dropped. Use a deep-equality library for robust comparison.

### Get the value at given path of an object

Follow a dot-separated path, stopping at a missing step. https://1loc.dev/object/get-the-value-at-given-path-of-an-object/

```javascript
function getValue({ path, object }) { return path.split('.').reduce((value, key) => (value == null ? undefined : value[key]), object) ?? null; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Missing paths return null here (undefined in the original), so the result is JSON-representable.

### Immutably rename object keys

Return a copy with keys renamed through a mapping. https://1loc.dev/object/immutably-rename-object-keys/

```javascript
function renameKeys({ keysMap, object }) { return Object.fromEntries(Object.entries(object).map(([key, value]) => [keysMap[key] || key, value])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Object.fromEntries replaces the original reduce with spread, which copied the accumulator on every key.

### Invert keys and values of an object

Swap every key with its value. https://1loc.dev/object/invert-keys-and-values-of-an-object/

```javascript
function invert(object) { return Object.fromEntries(Object.entries(object).map(([key, value]) => [value, key])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values become string keys; duplicates keep the last key, as the edge case shows.

### Extract values of a property from an array of objects

Pluck one field from every record. https://1loc.dev/object/extract-values-of-a-property-from-an-array-of-objects/

```javascript
function pluck({ objects, property }) { return objects.map(object => object[property] ?? null); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Missing fields become null (undefined in the original).

### Sort an object by its properties

Rebuild an object with its keys in sorted order. https://1loc.dev/object/sort-an-object-by-its-properties/

```javascript
function sortKeys(object) { return Object.fromEntries(Object.keys(object).sort().map(key => [key, object[key]])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Integer-like keys always come first in ascending numeric order, whatever you sort, as the edge case shows. Useful for stable JSON before hashing — but sign raw bytes, as webhooks do.

### Remove all null and undefined properties from an object

Drop keys whose value is null or undefined. https://1loc.dev/object/remove-all-null-and-undefined-properties-from-an-object/

```javascript
function removeNullish(object) { return Object.fromEntries(Object.entries(object).filter(([, value]) => value != null)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Only null and undefined are removed: 0, "" and false stay, as the edge case shows.

### Shallow copy an object

Copy own enumerable properties into a new object. https://1loc.dev/object/shallow-copy-an-object/

```javascript
function shallowCopy(object) { return { ...object }; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Nested objects are shared, not copied. Use structuredClone for a deep copy.

### Get unique objects from an array by key

Keep one record per key value, the last one seen. https://1loc.dev/object/get-unique-arr-obj/

```javascript
function uniqueBy({ objects, key }) { return [...new Map(objects.map(item => [item[key], item])).values()]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The last record per key wins, in the position of the first one — handy for keeping the latest state per recipient.

### Create an empty map that does not have properties

An object with no prototype: no inherited keys such as toString or __proto__. https://1loc.dev/object/create-an-empty-map-that-does-not-have-properties/

```javascript
function createDictionary() { return Object.create(null); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Keys from user input, such as "__proto__", stay ordinary data, as the last lines show.

## string

### Capitalize a string

Uppercase the first Unicode code point and preserve the remaining text. https://1loc.dev/string/capitalize-a-string/

```javascript
function capitalize(value) { const [first, ...rest] = Array.from(value); return first ? first.toUpperCase() + rest.join('') : ''; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Uppercasing can expand a character, such as ß into SS. This is not locale-aware title casing.

### Reverse a string

Reverse Unicode code points without splitting surrogate pairs. https://1loc.dev/string/reverse-a-string/

```javascript
function reverse(value) { return Array.from(value).reverse().join(''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Combining marks and joined emoji can still split: code points are not grapheme clusters.

### Check a palindrome

Compare a string with its code-point reversal. https://1loc.dev/string/check-if-a-string-is-a-palindrome/

```javascript
function palindrome(value) { return value === Array.from(value).reverse().join(''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Case, punctuation, spaces and Unicode normalization are significant.

### Create a simple URL slug

Normalize a Latin-text label into lowercase ASCII words separated by hyphens. https://1loc.dev/string/convert-a-string-to-url-slug/

```javascript
function slugify(value) { return value.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This deliberately produces ASCII slugs. Many non-Latin scripts become empty.

### Convert snake case to camel case

Uppercase a lowercase ASCII letter immediately after an underscore. https://1loc.dev/string/convert-snake-case-to-camel-case/

```javascript
function camelCase(value) { return value.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Consecutive underscores, digits and uppercase letters are preserved unless directly matched.

### Remove duplicate lines

Keep the first occurrence of every exact line while normalizing CRLF to LF. https://1loc.dev/string/remove-duplicate-lines-of-a-text-document/

```javascript
function uniqueLines(value) { return [...new Set(value.split(/\r?\n/))].join('\n'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Whitespace and case matter. One empty line is retained; line endings become LF.

### Check if a URL is absolute

Detect a scheme such as https: at the start of a URL string. https://1loc.dev/string/check-if-a-url-is-absolute/

```javascript
function isAbsoluteUrl(url) { return /^[a-z][a-z0-9+.-]*:/i.test(url); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A scheme is not a safety check: javascript: and data: URLs are absolute too. Allow-list https: before storing or following a URL, such as a webhook endpoint.

### Check if a path is relative

Return true unless the path starts with a slash or backslash, optionally after a drive or scheme. https://1loc.dev/string/check-if-a-path-is-relative/

```javascript
function isRelative(path) { return !/^([a-z]+:)?[\\/]/i.test(path); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A scheme without slashes, such as mailto: or data:, still counts as relative. Use the URL-absolute check for URLs.

### Convert a base64 encoded string to an Uint8Array

Decode base64 into its byte values. https://1loc.dev/string/convert-a-base64-encoded-string-to-an-uint8-array/

```javascript
function base64ToBytes(base64) { return Array.from(atob(base64), char => char.charCodeAt(0)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Returns plain numbers so the lab can show them; wrap the result with Uint8Array.from in your code.

### Convert an Uint8Array to a base64 encoded string

Encode byte values as base64 with btoa. https://1loc.dev/string/convert-an-uint8-array-to-a-base64-encoded-string/

```javascript
function bytesToBase64(bytes) { return btoa(String.fromCharCode(...bytes)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Spreading is fine for the lab’s 1,000 bytes. For files, use Buffer.from(bytes).toString("base64") in Node.js or encode in chunks.

### Check if a string consists of a repeated character sequence

Find the string inside itself doubled, past the first position. https://1loc.dev/string/check-if-a-string-consists-of-a-repeated-character-sequence/

```javascript
function consistsRepeatedSubstring(text) { return `${text}${text}`.indexOf(text, 1) !== text.length; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The empty string returns false. Comparison is by UTF-16 code units.

### Check if two strings are anagrams

Compare the sorted, lowercased characters of both strings. https://1loc.dev/string/check-if-two-strings-are-anagram/

```javascript
function areAnagram({ first, second }) { const sorted = text => Array.from(text.toLowerCase()).sort().join(''); return sorted(first) === sorted(second); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Spaces and punctuation count, as the edge case shows; strip them first for phrase anagrams.

### Convert a letter to its regional indicator emoji

Map a–z to the regional indicator symbols 🇦–🇿. https://1loc.dev/string/convert-a-letter-to-associate-emoji/

```javascript
function letterToEmoji(letter) { return String.fromCodePoint(letter.toLowerCase().charCodeAt(0) + 127365); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input is one ASCII letter. Two indicators side by side render as a country flag in many fonts.

### Sort the characters of a string in alphabetical order

Sort code points with an explicit English collation. https://1loc.dev/string/sort-the-characters-of-a-string-in-the-alphabetical-order/

```javascript
function sortCharacters(text) { return Array.from(text).sort((a, b) => a.localeCompare(b, 'en')).join(''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original used the runtime’s default locale, which can differ between machines; this version names the locale.

### Generate a hash of a string

Compute the 32-bit hash Java’s String.hashCode uses. https://1loc.dev/string/generate-a-hash-of-a-string/

```javascript
function hashString(text) { return text.split('').reduce((hash, char) => (Math.imul(31, hash) + char.charCodeAt(0)) | 0, 0); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Not cryptographic and collision-prone: use it for bucketing, never for integrity. To authenticate data use HMAC-SHA256, as in the webhook signature lab.

### Get the length of a string in bytes

Count UTF-8 bytes rather than characters. https://1loc.dev/string/get-the-length-of-a-string-in-bytes/

```javascript
function byteLength(text) { return new TextEncoder().encode(text).length; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). UTF-8 is what most APIs and email bodies use. Email header lines are limited to 998 bytes excluding CRLF (RFC 5322); measure bytes, not characters.

### Strip ANSI codes from a string

Remove terminal color and cursor escape sequences. https://1loc.dev/string/strip-ansi-codes-from-a-string/

```javascript
function stripAnsi(text) { return text.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, ''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Covers SGR colors and common CSI sequences, not every operating-system command sequence.

### Swap case of characters in a string

Uppercase lowercase letters and lowercase the rest. https://1loc.dev/string/swap-case-of-characters-in-a-string/

```javascript
function swapCase(text) { return Array.from(text).map(char => char === char.toLowerCase() ? char.toUpperCase() : char.toLowerCase()).join(''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Case mapping can change length: ß uppercases to SS.

### Convert a string to Pascal case

Join alphanumeric words, each starting with an uppercase letter. https://1loc.dev/string/convert-a-string-to-pascal-case/

```javascript
function toPascalCase(text) { return (text.match(/[a-zA-Z0-9]+/g) || []).map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Only ASCII letters and digits form words; accented letters split words.

### Convert a Windows file path to a Unix path

Use forward slashes and drop a drive letter or leading ./. https://1loc.dev/string/convert-a-windows-file-path-to-unix-path/

```javascript
function toUnixPath(path) { return path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, ''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The drive letter is discarded, not mapped to a mount point.

### Convert camel case to kebab case and vice versa

Switch a single identifier between camelCase and kebab-case. https://1loc.dev/string/convert-camel-case-to-kebab-case-and-vice-versa/

```javascript
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()); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original page offered two functions; here one takes the target as to: "kebab" or "camel".

### Count the number of words in a string

Count runs of non-whitespace characters. https://1loc.dev/string/count-the-number-of-words-in-a-string/

```javascript
function countWords(text) { return (text.match(/\S+/g) || []).length; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original split on whitespace and returned 1 for a blank string; this version returns 0.

### Get the file extension from a file name

Return the text after the last dot, or an empty string. https://1loc.dev/string/get-the-file-extension-from-a-file-name/

```javascript
function fileExtension(name) { const dot = name.lastIndexOf('.'); return dot > 0 ? name.slice(dot + 1) : ''; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original returned the whole name when there was no dot. A leading dot marks a hidden file, not an extension.

### Get the file name from a URL

Take the last path segment, ignoring the query and fragment. https://1loc.dev/string/get-the-file-name-from-a-url/

```javascript
function fileNameFromUrl(url) { const path = url.split(/[?#]/)[0]; return path.slice(path.lastIndexOf('/') + 1); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original kept the query string; this version drops ?… and #… first.

### Get the number of a character in a string

Split on a character and count the pieces. https://1loc.dev/string/get-the-number-of-a-character-in-a-string/

```javascript
function characterCount({ text, char }) { return text.split(char).length - 1; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). char is a single character; longer strings count non-overlapping occurrences.

### Normalize file path slashes

Collapse runs of slashes and backslashes into single forward slashes. https://1loc.dev/string/normalize-file-path-slashes/

```javascript
function normalizePath(path) { return path.replace(/[\\/]+/g, '/'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This also collapses the // after a URL scheme; do not apply it to URLs.

### Remove spaces from a string

Delete every whitespace character, including tabs and line breaks. https://1loc.dev/string/remove-spaces-from-a-string/

```javascript
function removeSpaces(text) { return text.replace(/\s/g, ''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). \s also matches non-breaking and other Unicode spaces.

### Repeat a string

Concatenate a string with itself a given number of times. https://1loc.dev/string/repeat-a-string/

```javascript
function repeat({ text, times }) { return text.repeat(times); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab caps the result at 16,000 characters before allocating it.

### Replace all line breaks with br elements

Turn LF and CRLF line breaks into <br>. https://1loc.dev/string/replace-all-line-breaks-with-br-elements/

```javascript
function nl2br(text) { return text.replace(/\r?\n/g, '<br>'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Escape the text first. Converting untrusted text to HTML without escaping is an injection risk — in a web page and in an HTML email.

### Replace all tab characters with spaces

Replace each tab with a fixed number of spaces. https://1loc.dev/string/replace-all-tab-characters-with-spaces/

```javascript
function tabsToSpaces({ text, spaces }) { return text.replaceAll('\t', ' '.repeat(spaces)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This does not align to tab stops; every tab becomes the same width.

### Mask the first characters of a string

Replace the first count characters with a mask character, keeping the length. https://1loc.dev/string/replace-the-first-given-number-of-characters-of-a-string-with-another-character/

```javascript
function maskStart({ text, count, mask }) { return text.slice(count).padStart(text.length, mask); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Masking for display is not tokenization; never store or log the original value.

### Reverse the order of lines of a text

Split on LF or CRLF and reverse the lines. https://1loc.dev/string/reverse-the-order-of-lines-of-a-text/

```javascript
function reverseLines(text) { return text.split(/\r?\n/).reverse().join('\n'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Line endings become LF.

### Sort lines of a text document in alphabetical order

Split into lines and sort them by UTF-16 code units. https://1loc.dev/string/sort-lines-of-a-text-document-in-the-alphabetical-order/

```javascript
function sortLines(text) { return text.split(/\r?\n/).sort().join('\n'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Default sort order puts uppercase before lowercase, as the edge case shows. Use localeCompare for human ordering.

### Trim slashes at the beginning and the end of a string

Remove leading and trailing forward slashes. https://1loc.dev/string/trim-slashes-at-the-beginning-and-the-end-of-a-string/

```javascript
function trimSlashes(text) { return text.replace(/^\/+|\/+$/g, ''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Inner slashes are kept.

### Trim the file extension from a file name

Remove the text from the last dot onward. https://1loc.dev/string/trim-the-file-extension-from-a-file-name/

```javascript
function trimExtension(name) { const dot = name.lastIndexOf('.'); return dot > 0 ? name.slice(0, dot) : name; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original turned ".env" into an empty string; a leading dot is kept here.

### Convert a string to camel case

Remove separators and uppercase the character after each one. https://1loc.dev/string/convert-a-string-to-camel-case/

```javascript
function toCamelCase(text) { return text.trim().replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : ''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A leading separator uppercases the first letter, as the edge case shows. The first word is otherwise kept as typed.

### Convert the name of an Excel column to a number

Read a column name as a base-26 number where A is 1. https://1loc.dev/string/convert-the-name-of-an-excel-column-to-number/

```javascript
function columnNumber(column) { return column.split('').reduce((total, letter) => total * 26 + parseInt(letter, 36) - 9, 0); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab accepts 1–6 letters (up to ZZZZZZ). Lowercase letters work too.

### Count the occurrences of a character in a string

Count code points equal to a given character. https://1loc.dev/string/count-the-occurrences-of-a-character-in-a-string/

```javascript
function countOccurrences({ text, char }) { return Array.from(text).filter(item => item === char).length; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Iterates code points, so emoji count once.

### Decapitalize a string

Lowercase the first code point and keep the rest. https://1loc.dev/string/decapitalize-a-string/

```javascript
function decapitalize(text) { const [first = '', ...rest] = Array.from(text); return first.toLowerCase() + rest.join(''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Not locale-aware: Turkish dotted İ needs toLocaleLowerCase("tr").

### Escape HTML special characters

Replace & < > " and ' with HTML entities. https://1loc.dev/string/escape-html-special-characters/

```javascript
function escapeHtml(text) { return text.replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Escape untrusted text before placing it in HTML, including HTML email templates. This protects text content and quoted attribute values, not URLs, scripts or CSS.

### Format a string

Replace {0}, {1}… placeholders with values in order. https://1loc.dev/string/format-a-string/

```javascript
function format({ template, values }) { return values.reduce((text, value, i) => text.replaceAll(`{${i}}`, String(value)), template); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Replacements run in order, so a value containing "{1}" is replaced again by the next value. Use a template engine with escaping for HTML.

### Get the base URL without any parameters

Drop the query string and fragment. https://1loc.dev/string/get-the-base-url-without-any-parameters/

```javascript
function baseUrl(url) { return url.split(/[?#]/)[0]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original removed only the query; a fragment is not a parameter either, so it is dropped too.

### Make the first character of a string lowercase

Lowercase only the first character. https://1loc.dev/string/make-the-first-character-of-a-string-lowercase/

```javascript
function lowercaseFirst(text) { return `${text.charAt(0).toLowerCase()}${text.slice(1)}`; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). charAt works on UTF-16 code units; for text that may start with an emoji, use the code-point version in Decapitalize a string.

### Prepend a line number to each line of a text document

Number lines from 1, right-aligned to two characters. https://1loc.dev/string/prepend-a-line-number-to-each-line-of-a-text-document/

```javascript
function prependNumbers(text) { return text.split(/\r?\n/).map((line, i) => `${String(i + 1).padStart(2, ' ')} ${line}`).join('\n'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Numbers above 99 widen the gutter. An empty text is one empty line.

### Replace multiple spaces with a single space

Collapse runs of two or more whitespace characters. https://1loc.dev/string/replace-multiple-spaces-with-a-single-space/

```javascript
function collapseSpaces(text) { return text.replace(/\s\s+/g, ' '); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A single tab or line break is left as it is, as the edge case shows.

### Trim a character from both ends

Remove a repeated character from the start and the end only. https://1loc.dev/string/trim-some-character/

```javascript
function trimCharacter({ text, char }) { const escaped = char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return text.replace(new RegExp(`^(?:${escaped})+|(?:${escaped})+$`, 'g'), ''); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original split on the character and joined with commas, which also removed inner characters; this version trims the ends only.

### Truncate a string at full words

Cut at the last space that fits, then add a suffix. https://1loc.dev/string/truncate-a-string-at-full-words/

```javascript
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}`; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original truncated strings exactly max long and returned only the suffix when the first word was too long; both are fixed.

### Unescape HTML special characters

Turn &amp; &lt; &gt; &quot; and &#39; back into characters in one pass. https://1loc.dev/string/unescape-html-special-characters/

```javascript
function unescapeHtml(text) { return text.replace(/&(?:amp|lt|gt|quot|#0*39);/g, entity => ({ '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"' })[entity] ?? "'"); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original replaced entities one after another, so "&amp;lt;" became "<". A single pass keeps it as "&lt;".

### Uppercase the first character of each word

Capitalize every space-separated word. https://1loc.dev/string/uppercase-the-first-character-of-each-word-in-a-string/

```javascript
function uppercaseWords(text) { return text.split(' ').map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(' '); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Only spaces separate words; this is not language-aware title case.

### Remove empty lines of a text document

Drop lines that are empty or whitespace only. https://1loc.dev/string/remove-empty-lines-of-a-text-document/

```javascript
function removeEmptyLines(text) { return text.split(/\r?\n/).filter(line => line.trim() !== '').join('\n'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Line endings become LF.

### Decode numeric HTML entities

Turn &#233; and &#xE9; style references into characters. https://1loc.dev/string/decode-html-entities/

```javascript
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; }); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Numeric references only; named ones such as &eacute; need an HTML parser. The original regex mishandled hexadecimal references.

## number

### Clamp a number to a range

Keep a number inside an inclusive minimum and maximum. https://1loc.dev/number/clamp-a-number-between-two-values/

```javascript
function clamp({ value, min, max }) { return Math.min(max, Math.max(min, value)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). All values must be finite numbers and min must not exceed max.

### Round to a number of digits

Apply decimal scaling and JavaScript rounding for display-oriented values. https://1loc.dev/number/round-a-number-to-a-given-number-of-digits/

```javascript
function roundTo({ value, digits }) { const factor = 10 ** digits; return Math.round(value * factor) / factor; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Binary floating-point explains the 1.005 edge case. This is not exact decimal arithmetic.

### Add an ordinal suffix to a number

Append st, nd, rd or th to a positive integer. https://1loc.dev/number/add-an-ordinal-suffix-to-a-number/

```javascript
function addOrdinal(n) { return `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). 11, 12 and 13 take th, as the edge case shows. English only; use Intl.PluralRules({ type: "ordinal" }) for other languages.

### Calculate Fibonacci numbers

Return the nth Fibonacci number with memoized recursion. https://1loc.dev/number/calculate-fibonacci-numbers/

```javascript
function fibonacci(n, memo = {}) { return memo[n] || (n <= 2 ? 1 : (memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo))); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab stops at n = 78, the largest Fibonacci number below Number.MAX_SAFE_INTEGER; use BigInt beyond it.

### Calculate the division of numbers

Divide the first number by each of the others in turn. https://1loc.dev/number/calculate-the-division-of-arguments/

```javascript
function division(values) { return values.reduce((a, b) => a / b); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original used rest arguments; the lab passes one array with at least one number. Dividing by 0 gives Infinity (null in JSON).

### Calculate the mod of a collection index

Wrap an index into 0…length−1, also for negative numbers. https://1loc.dev/number/calculate-the-mod-of-collection-index/

```javascript
function mod({ index, length }) { return ((index % length) + length) % length; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). JavaScript’s % keeps the sign of the dividend (-1 % 5 is -1); adding length first fixes it.

### Compute the greatest common divisor between two numbers

Apply Euclid’s algorithm. https://1loc.dev/number/compute-the-greatest-common-divisor-between-two-numbers/

```javascript
function gcd({ a, b }) { return b === 0 ? Math.abs(a) : gcd({ a: b, b: a % b }); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Returns a non-negative result; the original could return a negative divisor.

### Calculate the average of numbers

Divide the sum by the count. https://1loc.dev/number/calculate-the-average-of-arguments/

```javascript
function averageOf(values) { return values.reduce((a, b) => a + b) / values.length; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab passes one array with at least one number.

### Calculate the remainder of division of numbers

Apply % from left to right. https://1loc.dev/number/calculate-the-remainder-of-division-of-arguments/

```javascript
function remainder(values) { return values.reduce((a, b) => a % b); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). % keeps the sign of the dividend, as the edge case shows; use the collection-index mod for wrapping.

### Subtract numbers

Subtract each number from the first in turn. https://1loc.dev/number/subtract-arguments/

```javascript
function subtract(values) { return values.reduce((a, b) => a - b); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Binary floating-point: 0.3 − 0.1 is not exactly 0.2, as the edge case shows.

### Calculate the factorial of a number

Multiply the integers from 1 to n recursively. https://1loc.dev/number/calculate-the-factorial-of-a-number/

```javascript
function factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab stops at 18: 19! exceeds Number.MAX_SAFE_INTEGER. Use BigInt for larger values.

### Calculate the sum of numbers

Add numbers from left to right. https://1loc.dev/number/calculate-the-sum-of-arguments/

```javascript
function sumOf(values) { return values.reduce((a, b) => a + b); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Example: recipients per request — each recipient is one quota unit on Oveyon’s /v1/send.

### Convert a number to equivalent characters

Turn a zero-based index into a spreadsheet-style column name. https://1loc.dev/number/convert-a-number-to-equivalent-characters/

```javascript
function toChars(n) { return `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Zero-based: 0 is A and 25 is Z. The inverse of Convert the name of an Excel column to a number, minus one.

### Multiply numbers

Multiply numbers from left to right. https://1loc.dev/number/multiply-arguments/

```javascript
function multiply(values) { return values.reduce((a, b) => a * b); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab passes one array with at least one number.

### Truncate a number at decimal

Drop the fractional part toward zero. https://1loc.dev/number/truncate-a-number-at-decimal/

```javascript
function truncate(n) { return Math.trunc(n); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original ~~n only works within 32 bits: ~~3000000000 is -1294967296. Math.trunc works for every number.

### Convert a string to a number

Use unary plus. https://1loc.dev/number/convert-a-string-to-number/

```javascript
function toNumber(text) { return +text; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The empty string becomes 0 and invalid text becomes NaN (null in JSON). Validate first, or use Number.parseFloat for partial parsing.

### Convert decimal to binary recursively

Build the binary digits of a non-negative integer as a decimal-looking number. https://1loc.dev/number/convert-decimal-to-binary-recursively/

```javascript
function decToBinary(num) { return num === 0 ? 0 : (num % 2) + 10 * decToBinary(Math.floor(num / 2)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The result is a number whose digits are bits, so the lab stops at 65,535 to stay exact. For real work use num.toString(2).

### Prefix an integer with zeros

Pad a non-negative integer to a given width. https://1loc.dev/number/prefix-an-integer-with-zeros/

```javascript
function prefixWithZeros({ n, length }) { return String(n).padStart(length, '0'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Longer numbers are never cut, as the edge case shows. The original toFixed variant broke for numbers with as many digits as the width.

### Truncate a number to decimal places without rounding

Cut the decimal representation after a number of digits. https://1loc.dev/number/truncate-a-number-to-a-given-number-of-decimal-places-without-rounding/

```javascript
function toFixedDown({ n, digits }) { return Number(`${n}`.match(new RegExp(`^-?\\d+(?:\\.\\d{0,${digits}})?`))[0]); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Works on the decimal string, so floating-point drift does not round the result up.

### Wrap a number between two values

Map a number into [min, max) like an angle or a carousel index. https://1loc.dev/number/wrap-a-number-between-two-values/

```javascript
function wrap({ num, min, max }) { return ((((num - min) % (max - min)) + (max - min)) % (max - min)) + min; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). max is exclusive. The lab requires min < max.

### Get the arrays of digits from a number

Split a non-negative integer into its decimal digits. https://1loc.dev/number/get-the-arrays-of-digits-from-a-number/

```javascript
function digitize(n) { return [...`${n}`].map(digit => Number(digit)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Non-negative integers only: a minus sign or decimal point would not be a digit.

### Get the intersection range between two ranges

Return the overlap of two closed ranges, or an empty array. https://1loc.dev/number/get-the-intersection-range-between-two-ranges/

```javascript
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])]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Ranges are [start, end] with start ≤ end; touching ranges overlap in one point.

## misc

### Convert Celsius to Fahrenheit

Apply the temperature conversion without rounding the result. https://1loc.dev/misc/convert-celsius-to-fahrenheit/

```javascript
function toFahrenheit(value) { return value * 9 / 5 + 32; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This is a mathematical conversion. It does not enforce a physical temperature range.

### Convert hex to RGB

Expand #rgb if needed and read the red, green and blue channels. https://1loc.dev/misc/convert-hex-to-rgb/

```javascript
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)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Accepts #rgb and #rrggbb with or without #; alpha channels are outside this contract.

### Convert URL parameters to object

Read a query string into an object; repeated keys become arrays. https://1loc.dev/misc/convert-url-parameters-to-object/

```javascript
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 }), {}); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values are strings; + decodes to a space as in HTML forms.

### Convert 3 digits color to 6 digits color

Double each digit of a #rgb color. https://1loc.dev/misc/convert-3-digits-color-to-6-digits-color/

```javascript
function toFullHexColor(color) { return `#${(color.startsWith('#') ? color.slice(1) : color).split('').map(digit => `${digit}${digit}`).join('')}`; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input must be three hexadecimal digits, with or without #.

### Convert Fahrenheit to Celsius

Subtract 32 and multiply by 5/9. https://1loc.dev/misc/convert-fahrenheit-to-celsius/

```javascript
function fahrenheitToCelsius(fahrenheit) { return (fahrenheit - 32) * 5 / 9; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The inverse of Convert Celsius to Fahrenheit; results are not rounded.

### Get the value of a param from a URL

Parse an absolute URL and read one query parameter. https://1loc.dev/misc/get-the-value-of-a-param-from-a-url/

```javascript
function getParam({ url, param }) { return new URL(url).searchParams.get(param); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A missing parameter returns null. Repeated parameters return the first value; use getAll for every value.

### Convert RGB color to hex

Pack three 0–255 channels into a #rrggbb string. https://1loc.dev/misc/convert-rgb-color-to-hex/

```javascript
function rgbToHex({ red, green, blue }) { return `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The 1 << 24 term keeps leading zeros. Channels must be integers from 0 to 255.

### Convert cookie to object

Parse a Cookie header string into name–value pairs. https://1loc.dev/misc/convert-cookie-to-object/

```javascript
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()])); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original read document.cookie and split on every =, which cut values such as "abc=def"; this version parses any header string and splits on the first = only.

### Easing functions

Evaluate a common easing curve at progress t between 0 and 1. https://1loc.dev/misc/easing-functions/

```javascript
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]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original listed separate functions; one function selects the curve by name. Curves follow the gist the original cites (gre/1650294).

### Encode a URL component strictly

Percent-encode a value, including !'()* that encodeURIComponent leaves alone. https://1loc.dev/misc/encode-a-url/

```javascript
function encodeStrict(value) { return encodeURIComponent(value).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). RFC 3986 unreserved characters (- _ . ~) stay as they are, as the edge case shows. The original also encoded ~, which RFC 3986 leaves unreserved.

### Get the value of a cookie

Find one cookie by name in a Cookie header string. https://1loc.dev/misc/get-the-value-of-a-cookie/

```javascript
function getCookie({ cookie, name }) { const match = `; ${cookie}`.split(`; ${name}=`); return match.length > 1 ? match.pop().split(';').shift() : null; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A missing cookie returns null; the original returned the whole cookie string for an unknown name.

### Get the type of a variable as a string

Read the internal [[Class]] tag via Object.prototype.toString. https://1loc.dev/misc/get-type-of-a-variable-in-string/

```javascript
function getTypeOf(value) { return Object.prototype.toString.call(value).match(/\[object (.*)\]/)[1]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Distinguishes Array, Null, Date and RegExp where typeof says "object". Objects can override the tag with Symbol.toStringTag.

### Swap two variables

Exchange two values with array destructuring. https://1loc.dev/misc/swap-two-variables/

```javascript
function swap([a, b]) { [a, b] = [b, a]; return [a, b]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Destructuring works for any values. The original’s arithmetic tricks (a = b + ((b = a), 0)) only work for numbers and are harder to read.

### Decode a JWT token

Read the JSON payload of a JSON Web Token — without verifying it. https://1loc.dev/misc/decode-a-jwt-token/

```javascript
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(''))); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Decoding is not verification: anyone can forge a payload. Verify the signature with your JWT library before trusting any claim.

### Get the first defined and non-null value

Return the first item that is neither null nor undefined. https://1loc.dev/misc/get-the-first-defined-and-non-null-argument/

```javascript
function coalesce(values) { return values.find(item => item !== undefined && item !== null) ?? null; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). 0 and "" count as defined, as the example shows — unlike ||. The ?? operator does the same for two values.

### Convert a Lab color to an LCH color

Turn a and b into chroma and hue degrees. https://1loc.dev/misc/convert-a-lab-color-to-an-lch-color/

```javascript
function labToLch([l, a, b]) { return [l, Math.hypot(a, b), ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Hue is normalized to 0–360°; the original could return negative hues, as the edge case would.

### Convert an LCH color to a Lab color

Turn chroma and hue degrees back into a and b. https://1loc.dev/misc/convert-an-lch-color-to-a-lab-color/

```javascript
function lchToLab([l, c, h]) { return [l, Math.cos((h * Math.PI) / 180) * c, Math.sin((h * Math.PI) / 180) * c]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Floating-point trigonometry leaves tiny residues such as 6e-16, as the edge case shows; round for display.

### Check if the code is running in Jest

Look for the JEST_WORKER_ID variable that Jest sets in its workers. https://1loc.dev/misc/check-if-the-code-is-running-in-jest/

```javascript
function isRunningInJest() { return typeof process !== 'undefined' && process.env.JEST_WORKER_ID !== undefined; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Other runners, such as Vitest or node --test, are not detected.

### Check if the code is running in NodeJS

Look for process.versions.node. https://1loc.dev/misc/check-if-the-code-is-running-in-node-js/

```javascript
function isNode() { return typeof process !== 'undefined' && process.versions?.node != null; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Node-compatible runtimes such as Bun also set process.versions.node, so this detects compatibility, not Node.js itself. The browser tests confirm it returns false in Chromium.

### Check if the code is running in the browser

Look for the window and document globals. https://1loc.dev/misc/check-if-the-code-is-running-in-the-browser/

```javascript
function isBrowser() { return typeof window === 'object' && typeof document === 'object'; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Returns false in web and service workers, which have no document, and in Node.js, as the unit tests confirm.

### Clear all cookies

Expire every cookie that JavaScript can see on the current path. https://1loc.dev/misc/clear-all-cookies/

```javascript
function clearCookies() {
  for (const cookie of document.cookie.split(';')) {
    const name = cookie.split('=')[0].trim();
    if (name) document.cookie = `${name}=; Max-Age=0; path=/`;
  }
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). HttpOnly cookies, such as most session cookies, are invisible to JavaScript; only the server can clear them with Set-Cookie.

### Detect dark mode

Read the prefers-color-scheme media feature. https://1loc.dev/misc/detect-dark-mode/

```javascript
function isDarkMode() { return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The preference can change while the page is open: listen for the change event on the MediaQueryList.

### Emulate a dice throw

Return an integer from 1 to 6. https://1loc.dev/misc/emulate-a-dice-throw/

```javascript
function throwDice() { return Math.floor(Math.random() * 6) + 1; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original’s ~~ truncates like Math.floor only for non-negative numbers below 2³¹; Math.floor states the intent.

### Generate an unique and increment id

Create a counter that returns 0, 1, 2… on successive calls. https://1loc.dev/misc/generate-an-unique-and-increment-id/

```javascript
function createIdGenerator(start = 0) {
  let id = start;
  return () => id++;
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original assigned to an undeclared id: a ReferenceError in strict mode and ES modules, a leaked global otherwise.

### Redirect the page to HTTPS if it is in HTTP

Replace an http: address with the same address over https:. https://1loc.dev/misc/redirect-the-page-to-https-if-it-is-in-http/

```javascript
function redirectToHttps() {
  if (location.protocol !== 'http:') return;
  const url = new URL(location.href);
  url.protocol = 'https:';
  location.replace(url);
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A client-side redirect runs after the insecure page has loaded. Redirect at the server or CDN with a 301, and send Strict-Transport-Security so browsers stop requesting HTTP.

### Run Promises in sequence

Start each task after the previous one finishes and collect the results in order. https://1loc.dev/misc/run-promises-in-sequence/

```javascript
async function runInSequence(tasks) {
  const results = [];
  for (const task of tasks) results.push(await task());
  return results;
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Pass functions that start the work, not promises: a promise is already running once it exists. The original took promises, so it ordered the results but not the work, as the last lines show.

### Wait for an amount of time

Return a promise that resolves after the given milliseconds. https://1loc.dev/misc/wait-for-an-amount-of-time/

```javascript
function wait(milliseconds) { return new Promise(resolve => setTimeout(resolve, milliseconds)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). setTimeout is a minimum delay, not a schedule: a busy event loop or a background tab can delay it much longer.

### Wait for the next event loop

Resolve after the current task, letting queued timers, I/O and rendering run. https://1loc.dev/misc/wait-for-the-next-event-loop/

```javascript
function nextTask() { return new Promise(resolve => setTimeout(resolve, 0)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Promise callbacks (microtasks) still run before the timer, as the example shows.

## date & time

### Compare two dates

Compare validated ISO calendar dates in UTC and return -1, 0 or 1. https://1loc.dev/date-time/compare-two-dates/

```javascript
function compareDates({ first, second }) { return Math.sign(new Date(first).getTime() - new Date(second).getTime()); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The lab requires real YYYY-MM-DD calendar dates and validates before execution.

### Add AM PM suffix to an hour

Turn an hour from 0 to 23 into a 12-hour label with am or pm. https://1loc.dev/date-time/add-am-pm-suffix-to-an-hour/

```javascript
function suffixAmPm(hour) { return `${hour % 12 === 0 ? 12 : hour % 12}${hour < 12 ? 'am' : 'pm'}`; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Input is an integer hour from 0 to 23.

### Calculate the number of days between two dates

Count whole calendar days between two YYYY-MM-DD dates. https://1loc.dev/date-time/calculate-the-number-of-difference-days-between-two-dates/

```javascript
function diffDays({ first, second }) { return Math.round(Math.abs(Date.parse(second) - Date.parse(first)) / 86400000); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Both dates are UTC calendar days, so daylight-saving changes cannot add or lose an hour. The original rounded local Date differences up with Math.ceil.

### Convert a date to YYYY-MM-DD format

Format an ISO date-time as its UTC calendar date. https://1loc.dev/date-time/convert-a-date-to-yyyy-mm-dd-format/

```javascript
function formatYmd(dateTime) { return new Date(dateTime).toISOString().slice(0, 10); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). This is the UTC date. A local evening can already be tomorrow in UTC, as the edge case shows.

### Convert seconds to hh:mm:ss format

Format a whole number of seconds as zero-padded hours, minutes and seconds. https://1loc.dev/date-time/convert-seconds-to-hh-mm-ss-format/

```javascript
function formatSeconds(seconds) { return [Math.floor(seconds / 3600), Math.floor(seconds % 3600 / 60), seconds % 60].map(part => String(part).padStart(2, '0')).join(':'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Hours keep counting past 24. The original toISOString version wrapped around after one day.

### Calculate the number of months between two dates

Count calendar month boundaries from start to end. https://1loc.dev/date-time/calculate-the-number-of-months-between-two-dates/

```javascript
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()); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Days are ignored: January 31 to February 1 counts as one month. An end before the start returns 0.

### Extract year, month, day, hour, minute, second and millisecond from a date

Split the UTC ISO string into its numeric parts. https://1loc.dev/date-time/extract-year-month-day-hour-minute-second-and-millisecond-from-a-date/

```javascript
function extract(dateTime) { return new Date(dateTime).toISOString().split(/[^0-9]/).slice(0, -1); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Parts are zero-padded strings in UTC, as in the original; an offset shifts them, as the edge case shows.

### Get the current timestamp in seconds

Convert a date-time to whole Unix seconds. https://1loc.dev/date-time/get-the-current-timestamp-in-seconds/

```javascript
function unixSeconds(now) { return Math.floor(Date.parse(now) / 1000); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). now is an input so the result is testable; pass new Date().toISOString(), or use Math.floor(Date.now() / 1000).

### Get the first date in the month of a date

Set the UTC day of the month to 1. https://1loc.dev/date-time/get-the-first-date-in-the-month-of-a-date/

```javascript
function firstDateOfMonth(date) { const d = new Date(date); d.setUTCDate(1); return d.toISOString().slice(0, 10); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Works on UTC calendar dates; the original built a local Date at midnight.

### Get the total number of days in a year

Return 366 for Gregorian leap years and 365 otherwise. https://1loc.dev/date-time/get-the-total-number-of-days-in-a-year/

```javascript
function daysInYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Proleptic Gregorian rules: 1900 is not a leap year, 2000 is.

### Set the time of a date to midnight

Return the start of the UTC day of a date-time. https://1loc.dev/date-time/initialize-the-current-date-but-set-time-to-midnight/

```javascript
function midnightUtc(now) { const d = new Date(now); d.setUTCHours(0, 0, 0, 0); return d.toISOString(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original used local midnight via setHours; this version is UTC so it is the same on every server. Use setHours for the reader’s local day.

### Format a date for the given locale

Use Intl.DateTimeFormat with an explicit locale and time zone. https://1loc.dev/date-time/format-a-date-for-the-given-locale/

```javascript
function formatDate({ date, locale }) { return new Intl.DateTimeFormat(locale, { timeZone: 'UTC' }).format(new Date(date)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). timeZone: "UTC" keeps a YYYY-MM-DD date on the same day; without it a local time zone west of UTC shows the previous day.

### Get the current quarter of a date

Map the month to a quarter from 1 to 4. https://1loc.dev/date-time/get-the-current-quarter-of-a-date/

```javascript
function quarter(date) { return Math.ceil((new Date(date).getUTCMonth() + 1) / 3); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Calendar quarters; fiscal years that start in another month need an offset.

### Get the day of the year from a date

Count days from January 1, which is day 1. https://1loc.dev/date-time/get-the-day-of-the-year-from-a-date/

```javascript
function dayOfYear(date) { return Math.round((Date.parse(date) - Date.parse(`${date.slice(0, 4)}-01-01`)) / 86400000) + 1; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). UTC dates, so daylight-saving changes cannot shift the count; the original subtracted local Date objects.

### Get the last date in the month of a date

Step to day 0 of the next month in UTC. https://1loc.dev/date-time/get-the-last-date-in-the-month-of-a-date/

```javascript
function lastDateOfMonth(date) { const d = new Date(date); d.setUTCMonth(d.getUTCMonth() + 1, 0); return d.toISOString().slice(0, 10); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Day 0 of a month is the last day of the previous one — the same trick as the original, in UTC.

### Get the month name of a date

Look up the English month name of a date. https://1loc.dev/date-time/get-the-month-name-of-a-date/

```javascript
function monthName(date) { return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][new Date(date).getUTCMonth()]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). English only. For other languages use new Intl.DateTimeFormat(locale, { month: "long", timeZone: "UTC" }).

### Get the tomorrow date

Add one calendar day in UTC. https://1loc.dev/date-time/get-the-tomorrow-date/

```javascript
function tomorrow(date) { const d = new Date(date); d.setUTCDate(d.getUTCDate() + 1); return d.toISOString().slice(0, 10); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original’s second variant added 24 hours, which is not one day across a daylight-saving change.

### Get the weekday of a date

Look up the English weekday name of a date. https://1loc.dev/date-time/get-the-weekday-of-a-date/

```javascript
function weekday(date) { return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][new Date(date).getUTCDay()]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). English only; Intl.DateTimeFormat with { weekday: "long" } localizes it.

### Sort an array of dates

Sort dates ascending or descending without changing the input. https://1loc.dev/date-time/sort-an-array-of-dates/

```javascript
function sortDates({ dates, order = 'asc' }) { const sorted = [...dates].sort((a, b) => Date.parse(a) - Date.parse(b)); return order === 'desc' ? sorted.reverse() : sorted; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original descending comparator returned a boolean, which sort treats inconsistently; a numeric difference is required. It also sorted in place.

### Determine one year from a date

Add one to the UTC year. https://1loc.dev/date-time/determine-one-year-from-now/

```javascript
function plusOneYear(date) { const d = new Date(date); d.setUTCFullYear(d.getUTCFullYear() + 1); return d.toISOString().slice(0, 10); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). February 29 rolls over to March 1 in a non-leap year, as the edge case shows; clamp to February 28 if your contract requires it.

### Get the number of days in a given month

Read day 0 of the next month for a 1-based month. https://1loc.dev/date-time/get-the-number-of-days-in-given-month/

```javascript
function daysInMonth({ year, month }) { const d = new Date(0); d.setUTCFullYear(year, month, 0); return d.getUTCDate(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original comment called the month zero-based, but new Date(year, month, 0) gives the length of a 1-based month; this page says so explicitly.

### Get the yesterday date

Subtract one calendar day in UTC. https://1loc.dev/date-time/get-the-yesterday-date/

```javascript
function yesterday(date) { const d = new Date(date); d.setUTCDate(d.getUTCDate() - 1); return d.toISOString().slice(0, 10); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Calendar days, not 24-hour steps.

### Get hours and minutes from decimal time

Split decimal hours into whole hours and whole minutes. https://1loc.dev/date-time/get-hours-and-minutes-from-decimal-time/

```javascript
function hoursAndMinutes(value) { return [Math.floor(value), Math.floor((value * 60) % 60)]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Minutes are floored, not rounded, as the edge case shows. The lab accepts 0 or more hours.

### Get the timezone string

Read the runtime’s IANA time zone, such as America/Sao_Paulo. https://1loc.dev/date-time/get-the-timezone-string/

```javascript
function getTimezone() { return Intl.DateTimeFormat().resolvedOptions().timeZone; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Returns the zone of the runtime: the visitor’s in a browser, the server’s (often UTC) in Node.js. Store instants in UTC and convert for display.

## math

### Convert degrees to radians

Multiply by π and divide by 180. https://1loc.dev/math/convert-degrees-to-radians/

```javascript
function degreesToRadians(degrees) { return degrees * Math.PI / 180; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Results are binary floating-point approximations of π multiples.

### Check if a rectangle contains another one

Compare corners: a contains b when b’s corners sit inside or on a’s edges. https://1loc.dev/math/check-if-a-rectangle-contains-other-one/

```javascript
function contains({ a, b }) { return a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). (x1, y1) is the top-left and (x2, y2) the bottom-right corner; the lab requires x1 ≤ x2 and y1 ≤ y2.

### Check if a rectangle overlaps another one

Two rectangles overlap when they overlap on both axes. https://1loc.dev/math/check-if-a-rectangle-overlaps-other-one/

```javascript
function overlaps({ a, b }) { return a.x1 < b.x2 && b.x1 < a.x2 && a.y1 < b.y2 && b.y1 < a.y2; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original combined the axes with ||, so rectangles side by side at different heights counted as overlapping. Both axes must overlap.

### Calculate the angle of a line defined by two points

Use Math.atan2 for the angle from the x axis, in radians or degrees. https://1loc.dev/math/calculate-the-angle-of-a-line-defined-by-two-points/

```javascript
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; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). atan2 handles every quadrant, unlike atan(dy / dx). The result is in (−π, π].

### Calculate the distance between two points

Apply the Pythagorean theorem with Math.hypot. https://1loc.dev/math/calculate-the-distance-between-two-points/

```javascript
function distance({ p1, p2 }) { return Math.hypot(p2.x - p1.x, p2.y - p1.y); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Math.hypot avoids overflow in intermediate squares that Math.sqrt(dx² + dy²) can hit.

### Calculate the linear interpolation between two numbers

Blend from a to b by an amount between 0 and 1. https://1loc.dev/math/calculate-the-linear-interpolation-between-two-numbers/

```javascript
function lerp({ a, b, amount }) { return (1 - amount) * a + amount * b; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Amounts outside 0–1 extrapolate, as the edge case shows; clamp first when you need to stay in range.

### Normalize the ratio of a number in a range

Map a value in [min, max] to [0, 1]. https://1loc.dev/math/normalize-the-ratio-of-a-number-in-a-range/

```javascript
function normalizeRatio({ value, min, max }) { return (value - min) / (max - min); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values outside the range give ratios outside 0–1. The lab requires min < max.

### Calculate the midpoint between two points

Average the x and y coordinates. https://1loc.dev/math/calculate-the-midpoint-between-two-points/

```javascript
function midpoint({ p1, p2 }) { return [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Returns [x, y] as in the original.

### Check if a point is inside a rectangle

Compare the point with the rectangle’s edges. https://1loc.dev/math/check-if-a-point-is-inside-a-rectangle/

```javascript
function isInside({ point, rect }) { return point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Points on an edge are outside, as the edge case shows.

### Round a number to the nearest multiple of a given value

Divide, round and multiply back. https://1loc.dev/math/round-a-number-to-the-nearest-multiple-of-a-given-value/

```javascript
function roundNearest({ value, nearest }) { return Math.round(value / nearest) * nearest; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Math.round rounds .5 up, toward +∞. Fractional steps can produce floating-point noise.

### Convert radians to degrees

Multiply by 180 and divide by π. https://1loc.dev/math/convert-radians-to-degrees/

```javascript
function radiansToDegrees(radians) { return radians * 180 / Math.PI; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Results are floating-point approximations.

### Calculate the midpoint of a given range

Average the two ends of a [from, to] range. https://1loc.dev/math/calculate-the-midpoint-of-a-given-range/

```javascript
function rangeMidpoint([from, to]) { return (from + to) / 2; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The order of the ends does not matter.

### Linear scale a number between ranges

Map a value from one range onto another. https://1loc.dev/math/linear-scale-number-in-ranges/

```javascript
function linearScale({ value, inMin, inMax, outMin, outMax }) { return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Output ranges may be reversed, as the edge case shows. The lab requires inMin ≠ inMax.

### Linear scale of a number between two ranges

The arrow-function form of the same mapping. https://1loc.dev/math/linear-scale-of-a-number-between-two-ranges/

```javascript
function scale({ value, from, to }) { return ((value - from[0]) * (to[1] - to[0])) / (from[1] - from[0]) + to[0]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values outside the input range extrapolate, as the edge case shows.

## email

### Convert an email domain to punycode

Keep the local part and convert an international domain to its ASCII xn-- form. https://1loc.dev/email/convert-an-email-domain-to-punycode/

```javascript
function toAsciiAddress(address) { const at = address.lastIndexOf('@'); return `${address.slice(0, at)}@${new URL(`http://${address.slice(at + 1)}`).hostname}`; }
```

Written by Oveyon (MIT). Oveyon accepts ASCII addresses only: an international domain must be sent in its xn-- form, anything else is refused with address_not_ascii.

### Get the domain of an email address

Take the part after the last @ and lowercase it, for domain checks and grouping. https://1loc.dev/email/get-the-domain-of-an-email-address/

```javascript
function emailDomain(address) { return address.slice(address.lastIndexOf('@') + 1).toLowerCase(); }
```

Written by Oveyon (MIT). The last @ separates the domain, so a quoted local part containing @ still works. This does not validate the address.

### Mask an email address for logs

Keep the first character and the domain; hide the rest of the local part. https://1loc.dev/email/mask-an-email-address/

```javascript
function maskEmail(address) { return `${address.slice(0, 1)}•••${address.slice(address.lastIndexOf('@'))}`; }
```

Written by Oveyon (MIT). Masking reduces exposure in logs; it is not anonymization, and the domain stays visible.

### Normalize an email address for comparison

Trim whitespace and lowercase only the domain, preserving the local part. https://1loc.dev/email/normalize-an-email-address/

```javascript
function normalizeEmail(address) { const value = address.trim(); const at = value.lastIndexOf('@'); return `${value.slice(0, at)}@${value.slice(at + 1).toLowerCase()}`; }
```

Written by Oveyon (MIT). The local part is kept as typed: its case rules belong to the receiving server.

### Read a Retry-After header

Turn delay-seconds or an HTTP date into milliseconds to wait, never negative. https://1loc.dev/email/parse-a-retry-after-header/

```javascript
function retryAfterMs({ retryAfter, date }) { const seconds = Number(retryAfter); return Math.max(0, Number.isFinite(seconds) ? seconds * 1000 : Date.parse(retryAfter) - Date.parse(date)); }
```

Written by Oveyon (MIT). An HTTP date is compared with the response’s own Date header, not your clock, so clock skew cannot shorten the wait. The lab accepts delay-seconds from 0 to 86,400.

### Compute a backoff delay with full jitter

Double the window on every attempt, cap it, then pick a point inside it. https://1loc.dev/email/compute-an-exponential-backoff-delay/

```javascript
function backoffMs({ attempt, baseMs, capMs, random }) { return Math.round(random * Math.min(capMs, baseMs * 2 ** attempt)); }
```

Written by Oveyon (MIT). random is an input so the result is testable; pass Math.random() in production. Honor a Retry-After header when the server sends one.

### Build an idempotency key from an event

Join a scope, a business id and a version into one stable, colon-separated key. https://1loc.dev/email/build-an-idempotency-key/

```javascript
function idempotencyKey({ scope, id, version }) { return [scope, id, version].map(part => encodeURIComponent(String(part))).join(':'); }
```

Written by Oveyon (MIT). Derive the key from the business event, never from time or randomness: a retry must send the same key.

### Classify an SMTP reply

Read the reply code and enhanced status code, and tell a temporary failure from a permanent one. https://1loc.dev/email/classify-an-smtp-reply/

```javascript
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' }; }
```

Written by Oveyon (MIT). Reply classes follow RFC 5321: 2xx success, 3xx intermediate, 4xx transient, 5xx permanent. Enhanced codes (RFC 3463, class.subject.detail) refine the reason; servers may omit them.

### Build a DMARC record

Compose the TXT value for _dmarc.<domain> from a policy and an optional report address. https://1loc.dev/email/build-a-dmarc-record/

```javascript
function dmarcRecord({ policy, rua }) { return ['v=DMARC1', `p=${policy}`, ...(rua ? [`rua=${rua}`] : [])].join('; '); }
```

Written by Oveyon (MIT). Publish the value as a TXT record at _dmarc.<your-domain>; v=DMARC1 must come first (RFC 7489). Start with p=none and aggregate reports, then move to quarantine and reject once SPF or DKIM alignment holds.

### Parse a DMARC record

Split a published DMARC TXT value into its tags. https://1loc.dev/email/parse-a-dmarc-record/

```javascript
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()])); }
```

Written by Oveyon (MIT). Tag names are lowercased; values are kept as published. Unknown tags are returned, not validated.

## DOM

### Check if a given DOMRect is contained within another DOMRect

True when the target lies inside the container or on its edges. https://1loc.dev/dom/check-if-a-given-dom-rect-is-contained-within-another-dom-rect/

```javascript
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; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Pass rects from getBoundingClientRect() or plain { x, y, width, height } objects. The original read left and top, which plain objects lack.

### Check if two DOMRects intersect

Two rects intersect when they meet on both axes. https://1loc.dev/dom/check-if-two-dom-rects-intersect/

```javascript
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; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Touching edges count as intersecting, as the edge case shows. For a strict overlap use < and >, as in Check if a rectangle overlaps another one.

### Compare two DOMRects for size and position match

Compare x, y, width and height exactly. https://1loc.dev/dom/compare-two-dom-rects-for-size-and-position-match/

```javascript
function sameRect({ a, b }) { return ['x', 'y', 'width', 'height'].every(key => a[key] === b[key]); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Exact comparison. Layout coordinates are often fractional, as the edge case shows; compare rendered positions with a tolerance such as Math.abs(a - b) < 0.5.

### Get the center point of a DOMRect

Return [x, y] of the rect’s center. https://1loc.dev/dom/get-the-center-point-of-a-dom-rect/

```javascript
function getCenter({ x, y, width, height }) { return [x + width / 2, y + height / 2]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Coordinates are in the rect’s own space: viewport pixels for getBoundingClientRect(). Add window.scrollX and scrollY for document coordinates.

### Calculate the distance to the bottom of a page

Pixels left to scroll before the end of the page. https://1loc.dev/dom/calculate-the-distance-to-the-bottom-of-a-page/

```javascript
function distanceToBottom() { return document.documentElement.scrollHeight - window.innerHeight - window.scrollY; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). document.documentElement.scrollHeight measures the whole page. The original used document.body.scrollHeight, which can differ when body has margins or a fixed height.

### Check if an element has CSS overflow

True when either axis is styled to scroll: overflow auto or scroll. https://1loc.dev/dom/check-if-an-element-has-css-overflow/

```javascript
function hasCssOverflow(element) { const { overflowX, overflowY } = getComputedStyle(element); return [overflowX, overflowY].some(value => ['auto', 'scroll'].includes(value)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original read the overflow shorthand, which is "hidden auto" when the axes differ, as the last line shows; reading overflowX and overflowY handles both.

### Check if an element has overflow

True when the content is larger than the element’s visible box. https://1loc.dev/dom/check-if-an-element-has-overflow/

```javascript
function hasOverflow(element) { return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Compares content size with the visible box, whatever the overflow style: use it to decide whether to show a “Show more” control.

### Check if an element is a descendant of another

True when child is inside parent, at any depth. https://1loc.dev/dom/check-if-an-element-is-a-descendant-of-another/

```javascript
function isDescendant(child, parent) { return child !== parent && parent.contains(child); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Node.contains returns true for the node itself, as the last line shows, so the original called an element its own descendant.

### Check if an element is focused

Compare the element with document.activeElement. https://1loc.dev/dom/check-if-an-element-is-focused/

```javascript
function hasFocus(element) { return element === document.activeElement; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Inside shadow DOM, document.activeElement is the shadow host; element.matches(":focus") checks the element itself.

### Check if the touch events are supported

True when the browser exposes touch events or reports touch points. https://1loc.dev/dom/check-if-the-touch-events-are-supported/

```javascript
function touchSupported() { return 'ontouchstart' in window || navigator.maxTouchPoints > 0; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Touch support is not touch use: many laptops have both. For layout, the pointer and hover media features describe the primary input, as the last line shows.

### Check if user scrolls to the bottom of the page

True when the viewport has reached the end of the page. https://1loc.dev/dom/check-if-user-scrolls-to-the-bottom-of-the-page/

```javascript
function isAtBottom(tolerance = 1) { const { scrollHeight, clientHeight } = document.documentElement; return scrollHeight - clientHeight - window.scrollY <= tolerance; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A 1 px tolerance absorbs fractional scroll positions on zoomed and high-density screens, where the original’s exact comparison could stay false at the bottom.

### Detect Internet Explorer browser

Look for document.documentMode, which only Internet Explorer defines. https://1loc.dev/dom/detect-internet-explorer-browser/

```javascript
function isInternetExplorer() { return 'documentMode' in document; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Microsoft retired the Internet Explorer 11 desktop application in June 2022. Keep this only to show an upgrade notice in legacy intranets.

### Detect macOS browser

Guess whether the device is a Mac, iPhone or iPad from the platform string. https://1loc.dev/dom/detect-macos-browser/

```javascript
function isApplePlatform() { return /Mac|iPhone|iPad|iPod/.test(navigator.userAgentData?.platform ?? navigator.platform); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). navigator.platform is deprecated, and iPadOS reports "MacIntel" in desktop mode, so this cannot tell a Mac from an iPad. Chromium’s navigator.userAgentData is read where available.

### Get all siblings of an element

Return the other element children of the element’s parent. https://1loc.dev/dom/get-all-siblings-of-an-element/

```javascript
function siblings(element) { return element.parentElement ? [...element.parentElement.children].filter(child => child !== element) : []; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Element siblings only: text and comment nodes are skipped. The original threw a TypeError for an element without a parent; this version returns [].

### Get the position of an element relative to the document

Add the scroll offsets to the element’s viewport position. https://1loc.dev/dom/get-the-position-of-an-element-relative-to-the-document/

```javascript
function getPosition(element) { const rect = element.getBoundingClientRect(); return { left: rect.left + window.scrollX, top: rect.top + window.scrollY }; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original assigned to an undeclared r: a ReferenceError in strict mode and ES modules.

### Get the selected text

Read the text of the current document selection. https://1loc.dev/dom/get-the-selected-text/

```javascript
function getSelectedText() { return window.getSelection()?.toString() ?? ''; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Text selected inside an input or textarea is not part of the document selection: read value.slice(selectionStart, selectionEnd) on the field.

### Go back to the previous page

Move one step back in the session history. https://1loc.dev/dom/go-back-to-the-previous-page/

```javascript
function goBack() { history.back(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). history.back() is asynchronous: wait for popstate (same-document entries) or for the page to unload. It does nothing without a previous entry.

### Hide an element

Set the hidden attribute. https://1loc.dev/dom/hide-an-element/

```javascript
function hide(element) { element.hidden = true; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). hidden removes the element from layout and from the accessibility tree. A stylesheet rule such as display: flex overrides it; add [hidden] { display: none !important } to be safe.

### Insert an element after other one

Place an element right after a reference element. https://1loc.dev/dom/insert-an-element-after-other-one/

```javascript
function insertAfter(element, reference) { reference.after(element); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Element.after, before and replaceWith are the modern ChildNode methods; the original used parentNode.insertBefore with nextSibling.

### Insert an element before other one

Place an element right before a reference element. https://1loc.dev/dom/insert-an-element-before-other-one/

```javascript
function insertBefore(element, reference) { reference.before(element); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). before also accepts several nodes, and strings, which it inserts as text.

### Insert given HTML after an element

Parse an HTML string and insert it after the element. https://1loc.dev/dom/insert-given-html-after-an-element/

```javascript
function insertHtmlAfter(html, element) { element.insertAdjacentHTML('afterend', html); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The string is parsed as HTML: never pass user input, or an attacker can inject markup and event handlers (XSS). For untrusted text, use insertAdjacentText or create elements.

### Insert given HTML before an element

Parse an HTML string and insert it before the element. https://1loc.dev/dom/insert-given-html-before-an-element/

```javascript
function insertHtmlBefore(html, element) { element.insertAdjacentHTML('beforebegin', html); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The string is parsed as HTML: never pass user input (XSS). Inserted script elements do not run, but inline event handlers such as onerror do.

### Redirect to another page

Navigate to a URL, adding an entry to the history. https://1loc.dev/dom/redirect-to-another-page/

```javascript
function goTo(url) { location.assign(url); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A URL taken from user input is an open redirect, and a javascript: URL runs code. Accept only relative paths or an allow-list of origins.

### Reload the current page

Load the current document again. https://1loc.dev/dom/reload-the-current-page/

```javascript
function reload() { location.reload(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Reloading discards in-memory state. Prefer updating the part of the page that changed.

### Replace an element

Swap an element for another in the same position. https://1loc.dev/dom/replace-an-element/

```javascript
function replace(element, replacement) { element.replaceWith(replacement); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Element.replaceWith is the modern form of parentNode.replaceChild(newNode, oldNode), whose argument order is easy to swap by mistake.

### Scroll to top of the page

Scroll the window back to the top. https://1loc.dev/dom/scroll-to-top-of-the-page/

```javascript
function goToTop() { window.scrollTo(0, 0); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). If the page sets scroll-behavior: smooth, the scroll animates. Keep smooth scrolling inside a prefers-reduced-motion: no-preference query.

### Serialize form data

Turn a form’s fields into an object; repeated names become arrays. https://1loc.dev/dom/serialize-form-data/

```javascript
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]]));
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original tested the first value for truthiness, so an empty first value was dropped: alias would have been "ana.s".

### Show an element

Clear the hidden attribute and any inline display: none. https://1loc.dev/dom/show-an-element/

```javascript
function show(element) { element.hidden = false; element.style.removeProperty('display'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). If a stylesheet hides the element, it stays hidden; toggle a class instead.

### Strip HTML from a given text

Parse HTML in an inert document and return its text. https://1loc.dev/dom/strip-html-from-a-given-text/

```javascript
function stripHtml(html) { return new DOMParser().parseFromString(html, 'text/html').body.textContent ?? ''; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). DOMParser builds an inert document: scripts do not run and images do not load, so the second line is safe. The result is text; never insert the original HTML into the page.

### Toggle an element

Flip the hidden attribute. https://1loc.dev/dom/toggle-an-element/

```javascript
function toggle(element) { element.hidden = !element.hidden; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original’s first version set display to block, which breaks flex and grid containers; toggling hidden restores the element’s own display.

## function

### Logical xor operator

True when exactly one of two values is truthy. https://1loc.dev/function/logical-xor-operator/

```javascript
function xor([a, b]) { return Boolean(a) !== Boolean(b); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Operands are converted to booleans first. The original’s (a && !b) || (!a && b) returns an operand instead: for the edge case it returns "y", not true.

### Identity function

Return the argument unchanged. https://1loc.dev/function/identity-function/

```javascript
function identity(value) { return value; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Useful as a default transform: a pipeline step that does nothing, or values.filter(identity) to keep truthy items.

### Box handler

Chain transformations on a value, then unwrap the result. https://1loc.dev/function/box-handler/

```javascript
function boxHandler(value) { return { next: f => boxHandler(f(value)), done: f => f(value) }; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Each next returns a new box; nothing is mutated. An error thrown in a step propagates immediately.

### Check if a value is a function

True for anything callable: functions, arrows, async and generator functions, classes. https://1loc.dev/function/check-if-a-value-is-a-function/

```javascript
function isFunction(value) { return typeof value === 'function'; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original also returned true for a Promise, which is not callable. typeof is the reliable test, as the last line shows.

### Check if a value is a generator function

Read the internal tag of function* and async function* declarations. https://1loc.dev/function/check-if-a-value-is-a-generator-function/

```javascript
function isGeneratorFunction(value) { return ['[object GeneratorFunction]', '[object AsyncGeneratorFunction]'].includes(Object.prototype.toString.call(value)); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original missed async generator functions, as the second line shows. Symbol.toStringTag can spoof the tag.

### Check if a value is an async function

Read the internal tag of async function declarations and arrows. https://1loc.dev/function/check-if-a-value-is-an-async-function/

```javascript
function isAsyncFunction(value) { return Object.prototype.toString.call(value) === '[object AsyncFunction]'; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A regular function that returns a promise is not detected, as the second line shows, and code transpiled to older JavaScript loses the tag.

### Compose functions from left to right

Build one function that passes a value through each function in order. https://1loc.dev/function/compose-functions-from-left-to-right/

```javascript
function pipe(...fns) { return input => fns.reduce((value, fn) => fn(value), input); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Functions run in the order listed. With no functions, the input comes back unchanged.

### Compose functions

Build one function that applies functions from right to left, as in f(g(x)). https://1loc.dev/function/compose-functions/

```javascript
function compose(...fns) { return input => fns.reduceRight((value, fn) => fn(value), input); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The last function runs first, as in mathematical notation. pipe lists the same steps in execution order.

### Create a function that accepts a single argument

Wrap a function so it ignores every argument after the first. https://1loc.dev/function/create-a-function-that-accepts-a-single-argument/

```javascript
function unary(fn) { return value => fn(value); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). map passes (value, index, array), so parseInt received the index as its radix, as the first line shows. unary drops everything after the value.

### Create an empty function

A function that does nothing and returns undefined. https://1loc.dev/function/create-an-empty-function/

```javascript
function noop() {}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). A shared noop makes a safe default callback, as in send above.

### Curry a function

Collect arguments across calls until the function has as many as it declares. https://1loc.dev/function/curry-a-function/

```javascript
function curry(fn, ...args) { return fn.length <= args.length ? fn(...args) : (...more) => curry(fn, ...args, ...more); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The arity comes from fn.length, which stops at the first default or rest parameter: (a, b = 1) => … has length 1.

### Delay the evaluation of a function

Turn a call into a thunk: a function that runs the call only when invoked. https://1loc.dev/function/delay-the-evaluation-of-a-function/

```javascript
function thunkify(fn) { return (...args) => () => fn(...args); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The thunk runs fn every time it is called; wrap it with Execute a function once to keep the first result.

### Execute a function once

Run a function on the first call and return that result afterwards. https://1loc.dev/function/execute-a-function-once/

```javascript
function once(fn) {
  let done = false, result;
  return (...args) => {
    if (!done) { result = fn(...args); done = true; }
    return result;
  };
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Typical use: create one API client or connection pool lazily, on first use.

### Flip the arguments of a function

Call a function with its arguments in reverse order. https://1loc.dev/function/flip-the-arguments-of-a-function/

```javascript
function flip(fn) { return (...args) => fn(...args.reverse()); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). All arguments are reversed. For two arguments, (b, a) => fn(a, b) is the explicit form.

### Memoize a function

Cache results by argument so each input is computed once. https://1loc.dev/function/memoize-a-function/

```javascript
function memoize(fn) {
  const cache = new Map();
  return arg => {
    if (!cache.has(arg)) cache.set(arg, fn(arg));
    return cache.get(arg);
  };
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original cached with cache[arg] || …, so falsy results (0, "", false) were recomputed on every call: three calls above would have run three times. A Map also keeps 1 and "1" apart.

### Partially apply a function

Fix the first arguments now and pass the rest later. https://1loc.dev/function/partially-apply-a-function/

```javascript
function partial(fn, ...preset) { return (...rest) => fn(...preset, ...rest); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). fn.bind(null, …preset) is the built-in equivalent for functions that do not use this.

### Uncurry a function

Call a curried function with several arguments at once. https://1loc.dev/function/uncurry-a-function/

```javascript
function uncurry(fn, depth = 1) { return (...args) => args.slice(0, depth).reduce((next, arg) => next(arg), fn); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Arguments beyond depth are ignored, as in the original. depth must not exceed the curried function’s depth.

## random

### Generate a random boolean

Return true or false with equal probability. https://1loc.dev/random/generate-a-random-boolean/

```javascript
function randomBoolean() { return Math.random() < 0.5; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Math.random returns [0, 1), so < 0.5 splits it into two equal halves.

### Generate a random floating point number in given range

Scale Math.random into [min, max). https://1loc.dev/random/generate-a-random-floating-point-number-in-given-range/

```javascript
function randomFloat(min, max) { return Math.random() * (max - min) + min; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Results fall in [min, max). Floating-point rounding can occasionally produce max itself; clamp if that matters.

### Generate a random hex color

Return a #rrggbb color from 24 random bits. https://1loc.dev/random/generate-a-random-hex-color/

```javascript
function randomColor() { return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0')}`; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original’s second version omitted padStart, so colors below #100000 came out with fewer than six digits.

### Generate a random integer in given range

Return an integer from min to max, both included. https://1loc.dev/random/generate-a-random-integer-in-given-range/

```javascript
function randomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). min and max must be integers. Both ends are included.

### Generate a random IP address

Return a random IPv4 address from the ranges reserved for documentation. https://1loc.dev/random/generate-a-random-ip-address/

```javascript
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}`;
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). RFC 5737 reserves 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24 for documentation. They never belong to a real host, so fixtures and logs in examples cannot point at one.

### Generate a random sign

Return 1 or -1 with equal probability. https://1loc.dev/random/generate-a-random-sign/

```javascript
function randomSign() { return Math.random() < 0.5 ? -1 : 1; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Multiply by a magnitude for symmetric noise: randomSign() * magnitude.

### Generate a random string from given characters

Draw characters from an alphabet with a cryptographic generator, without bias. https://1loc.dev/random/generate-a-random-string-from-given-characters/

```javascript
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;
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Uses crypto.getRandomValues, a global in browsers and Node.js 19+. The original used Math.random, which is predictable and unsuitable for tokens.

### Generate a random string using Node crypto module

Return random bytes from node:crypto as a hex string. https://1loc.dev/random/generate-a-random-string-using-node-crypto-module/

```javascript
import { randomBytes } from 'node:crypto';

function randomToken(bytes = 32) { return randomBytes(bytes).toString('hex'); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). 32 bytes are 256 bits of entropy: 64 hex characters. toString("base64url") gives a shorter token for URLs.

### Generate a random string with given length

Return a lowercase Base32 identifier from a cryptographic generator. https://1loc.dev/random/generate-a-random-string-with-given-length/

```javascript
function randomId(length) {
  const alphabet = '0123456789abcdefghjkmnpqrstvwxyz';
  return Array.from(crypto.getRandomValues(new Uint8Array(length)), byte => alphabet[byte % 32]).join('');
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). 32 symbols (Crockford’s Base32, lowercase) divide 256 evenly, so every symbol is equally likely without rejection sampling. It omits i, l, o and u, which are easy to misread.

### Generate a random UUID

Return a version 4 UUID from the platform’s cryptographic generator. https://1loc.dev/random/generate-a-random-uuid/

```javascript
function uuid() { return crypto.randomUUID(); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). crypto.randomUUID() returns an RFC 9562 version 4 UUID. In browsers it requires a secure context: HTTPS or localhost.

### Generate a weighted random number in given range

Return an integer in [min, max) skewed toward min. https://1loc.dev/random/generate-a-weighted-random-number-in-given-range/

```javascript
function weightedRandom(min, max) { return Math.floor(Math.random() ** 2 * (max - min)) + min; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Squaring a uniform number skews results toward min: about 71% of draws land in the lower half, which the example checks. max is excluded.

### Generate an array of random integers in a given range

Return count integers from min to max, both included. https://1loc.dev/random/generate-an-array-of-random-integers-in-a-given-range/

```javascript
function randomIntegers(min, max, count) { return Array.from({ length: count }, () => Math.floor(Math.random() * (max - min + 1)) + min); }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Values can repeat. For distinct values, shuffle a range and take the first count, as in Get random items of an array.

### Get a random item and remove it from an array

Remove one random item from the array and return it. https://1loc.dev/random/get-a-random-item-and-remove-it-from-an-array/

```javascript
function takeRandomItem(values) { return values.splice(Math.floor(Math.random() * values.length), 1)[0]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Mutates the array. The original returned the one-item array from splice, such as [7], not the item; [0] unwraps it.

### Get a random item from an array

Return one item at a random index. https://1loc.dev/random/get-a-random-item-from-an-array/

```javascript
function randomItem(values) { return values[Math.floor(Math.random() * values.length)]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). An empty array returns undefined. The original’s | 0 behaves like Math.floor only below 2³¹.

### Get random items of an array

Return count distinct items in random order. https://1loc.dev/random/get-random-items-of-an-array/

```javascript
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);
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original spliced the array that reduce was walking, so reduce skipped the removed positions: asking for 8 of 10 items returned 5.

### Pick a random property of an object

Return one of the object’s own enumerable keys. https://1loc.dev/random/pick-a-random-property-of-an-object/

```javascript
function randomKey(object) { const keys = Object.keys(object); return keys[Math.floor(Math.random() * keys.length)]; }
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). Own enumerable string keys only; an empty object returns undefined. The original called Object.keys twice.

### Pick random lines from a text document

Split text into lines and return count of them in random order. https://1loc.dev/random/pick-random-lines-from-a-text-document/

```javascript
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);
}
```

Restored from the original 1loc collection by Nguyen Huu Phuoc and original contributors (MIT). The original had the same reduce-and-splice flaw as Get random items of an array: requesting more than half the lines returned fewer.
