Favorite JavaScript Utilities

in single line of code! No more!

Array

1.
Cast a value as an array
#
const castArray = (value) => (Array.isArray(value) ? value : [value]);
// Examples
castArray(1); // [1]
castArray([1, 2, 3]); // [1, 2, 3]
2.
Check if an array is empty
#
// `arr` is an array
const isEmpty = (arr) => !Array.isArray(arr) || arr.length === 0;
// Examples
isEmpty([]); // true
isEmpty([1, 2, 3]); // false
3.
Clone an array
#
// `arr` is an array
const clone = (arr) => arr.slice(0);
// Or
const clone = (arr) => [...arr];
// Or
const clone = (arr) => Array.from(arr);
// Or
const clone = (arr) => arr.map((x) => x);
// Or
const clone = (arr) => JSON.parse(JSON.stringify(arr));
// Or
const clone = (arr) => arr.concat([]);
4.
Compare two arrays regardless of order
#
// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify(a.sort()) === JSON.stringify(b.sort());
// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, 3, 2]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
5.
Compare two arrays
#
// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
// Or
const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
6.
Convert an array of objects to a single object
#
const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
// Or
const toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it]));
// Example
toObject(
[
{ id: '1', name: 'Alpha', gender: 'Male' },
{ id: '2', name: 'Bravo', gender: 'Male' },
{ id: '3', name: 'Charlie', gender: 'Female' },
],
'id'
);
/*
{
'1': { id: '1', name: 'Alpha', gender: 'Male' },
'2': { id: '2', name: 'Bravo', gender: 'Male' },
'3': { id: '3', name: 'Charlie', gender: 'Female' },
}
*/
7.
Convert an array of strings to numbers
#
const toNumbers = (arr) => arr.map(Number);
// Or
const toNumbers = (arr) => arr.map((x) => +x);
// Example
toNumbers(['2', '3', '4']); // [2, 3, 4]
8.
Count by the properties of an array of objects
#
const countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {});
// Example
countBy(
[
{ branch: 'audi', model: 'q8', year: '2019' },
{ branch: 'audi', model: 'rs7', year: '2020' },
{ branch: 'ford', model: 'mustang', year: '2019' },
{ branch: 'ford', model: 'explorer', year: '2020' },
{ branch: 'bmw', model: 'x7', year: '2020' },
],
'branch'
);
// { 'audi': 2, 'ford': 2, 'bmw': 1 }
9.
Count the occurrences of a value in an array
#
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
// Or
const countOccurrences = (arr, val) => arr.filter((item) => item === val).length;
// Examples
countOccurrences([2, 1, 3, 3, 2, 3], 2); // 2
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a'); // 3
10.
Count the occurrences of array elements
#
const countOccurrences = (arr) => arr.reduce((prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {});
// Examples
countOccurrences([2, 1, 3, 3, 2, 3]); // { '1': 1, '2': 2, '3': 3 }
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']); // { 'a': 3, 'b': 2, 'c': 1 }
11.
Create an array of cumulative sum
#
const accumulate = (arr) =>
arr.map(
(
(sum) => (value) =>
(sum += value)
)(0)
);
// Or
const accumulate = (arr) => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), []);
// Or
const accumulate = (arr) => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), 0);
// Example
accumulate([1, 2, 3, 4]); // [1, 3, 6, 10]
// 1 = 1
// 1 + 2 = 3
// 1 + 2 + 3 = 6
// 1 + 2 + 3 + 4 = 10
12.
Create an array of numbers in the given range
#
const range = (min, max) => [...Array(max - min + 1).keys()].map((i) => i + min);
// Or
const range = (min, max) =>
Array(max - min + 1)
.fill(0)
.map((_, i) => min + i);
// Or
const range = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i);
// Example
range(5, 10); // [5, 6, 7, 8, 9, 10]
13.
Create cartesian product
#
const cartesian = (...sets) => sets.reduce((acc, set) => acc.flatMap((x) => set.map((y) => [...x, y])), [[]]);
// Example
cartesian([1, 2], [3, 4]); // [ [1, 3], [1, 4], [2, 3], [2, 4] ]
/*
3 4
---------------
1 | [1, 3] [1, 4]
|
2 | [2, 3] [2, 4]
*/
14.
Empty an array
#
const empty = (arr) => (arr.length = 0);
// Or
arr = [];
15.
Find the closest number from an array
#
// Find the number from `arr` which is closest to `n`
const closest = (arr, n) => arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev));
// Or
const closest = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0];
// Example
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33
16.
Find the index of the last matching item of an array
#
const lastIndex = (arr, predicate) => arr.reduce((prev, curr, index) => (predicate(curr) ? index : prev), -1);
// Or
const lastIndex = (arr, predicate) => arr.map((item) => predicate(item)).lastIndexOf(true);
// Example
lastIndex([1, 3, 5, 7, 9, 2, 4, 6, 8], (i) => i % 2 === 1); // 4
lastIndex([1, 3, 5, 7, 9, 8, 6, 4, 2], (i) => i > 6); // 5
17.
Find the index of the maximum item of an array
#
const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);
// Examples
indexOfMax([1, 3, 9, 7, 5]); // 2
indexOfMax([1, 3, 7, 7, 5]); // 2
18.
Find the index of the minimum item of an array
#
const indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0);
// Examples
indexOfMin([6, 4, 8, 2, 10]); // 3
indexOfMin([6, 4, 2, 2, 10]); // 2
19.
Find the length of the longest string in an array
#
const findLongest = (words) => Math.max(...words.map((el) => el.length));
// Example
findLongest(['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']); // 6
20.
Find the maximum item of an array by given key
#
const maxBy = (arr, key) => arr.reduce((a, b) => (a[key] >= b[key] ? a : b), {});
// Example
const people = [
{ name: 'Bar', age: 24 },
{ name: 'Baz', age: 32 },
{ name: 'Foo', age: 42 },
{ name: 'Fuzz', age: 36 },
];
maxBy(people, 'age'); // { name: 'Foo', age: 42 }
21.
Find the maximum item of an array
#
const max = (arr) => Math.max(...arr);
22.
Find the minimum item of an array by given key
#
const minBy = (arr, key) => arr.reduce((a, b) => (a[key] < b[key] ? a : b), {});
// Example
const people = [
{ name: 'Bar', age: 24 },
{ name: 'Baz', age: 32 },
{ name: 'Foo', age: 42 },
{ name: 'Fuzz', age: 36 },
];
minBy(people, 'age'); // { name: 'Bar', age: 24 }
23.
Find the minimum item of an array
#
const min = (arr) => Math.min(...arr);
24.
Flatten an array
#
const flat = (arr) =>
[].concat.apply(
[],
arr.map((a) => (Array.isArray(a) ? flat(a) : a))
);
// Or
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), []);
// Or
// See the browser compatibility at https://caniuse.com/#feat=array-flat
const flat = (arr) => arr.flat();
// Example
flat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger']
25.
Get all arrays of consecutive elements
#
const getConsecutiveArrays = (arr, size) =>
size > arr.length ? [] : arr.slice(size - 1).map((_, i) => arr.slice(i, size + i));
// Examples
getConsecutiveArrays([1, 2, 3, 4, 5], 2); // [[1, 2], [2, 3], [3, 4], [4, 5]]
getConsecutiveArrays([1, 2, 3, 4, 5], 3); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
getConsecutiveArrays([1, 2, 3, 4, 5], 6); // []
26.
Get all n-th items of an array
#
const getNthItems = (arr, nth) => arr.filter((_, i) => i % nth === nth - 1);
// Examples
getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 2); // [2, 4, 6, 8]
getNthItems([1, 2, 3, 4, 5, 6, 7, 8, 9], 3); // [3, 6, 9]
27.
Get all subsets of an array
#
const getSubsets = (arr) => arr.reduce((prev, curr) => prev.concat(prev.map((k) => k.concat(curr))), [[]]);
// Examples
getSubsets([1, 2]); // [[], [1], [2], [1, 2]]
getSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
28.
Get indices of a value in an array
#
const indices = (arr, value) => arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), []);
// Or
const indices = (arr, value) => arr.map((v, i) => (v === value ? i : false)).filter(Boolean);
// Examples
indices(['h', 'e', 'l', 'l', 'o'], 'l'); // [2, 3]
indices(['h', 'e', 'l', 'l', 'o'], 'w'); // []
29.
Get the average of an array
#
const average = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
30.
Get the intersection of arrays
#
const getIntersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)));
// Examples
getIntersection([1, 2, 3], [2, 3, 4, 5]); // [2, 3]
getIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]); // [3]
31.
Get the rank of an array of numbers
#
const ranking = (arr) => arr.map((x, y, z) => z.filter((w) => w > x).length + 1);
// Examples
ranking([80, 65, 90, 50]); // [2, 3, 1, 4]
ranking([80, 80, 70, 50]); // [1, 1, 3, 4]
ranking([80, 80, 80, 50]); // [1, 1, 1, 4]
32.
Get the sum of an array of numbers
#
const sum = (arr) => arr.reduce((a, b) => a + b, 0);
33.
Get the unique values of an array
#
const unique = (arr) => [...new Set(arr)];
// Or
const unique = (arr) => arr.filter((el, i, array) => array.indexOf(el) === i);
// Or
const unique = (arr) => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), []);
34.
Get union of arrays
#
const union = (...arr) => [...new Set(arr.flat())];
// Example
union([1, 2], [2, 3], [3]); // [1, 2, 3]
35.
Group an array of objects by a key
#
const groupBy = (arr, key) =>
arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {});
// Example
groupBy(
[
{ branch: 'audi', model: 'q8', year: '2019' },
{ branch: 'audi', model: 'rs7', year: '2020' },
{ branch: 'ford', model: 'mustang', year: '2019' },
{ branch: 'ford', model: 'explorer', year: '2020' },
{ branch: 'bmw', model: 'x7', year: '2020' },
],
'branch'
);
/*
{
audi: [
{ branch: 'audi', model: 'q8', year: '2019' },
{ branch: 'audi', model: 'rs7', year: '2020' }
],
bmw: [
{ branch: 'bmw', model: 'x7', year: '2020' }
],
ford: [
{ branch: 'ford', model: 'mustang', year: '2019' },
{ branch: 'ford', model: 'explorer', year: '2020' }
],
}
*/
36.
Merge two arrays
#
// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
37.
Partition an array based on a condition
#
const partition = (arr, criteria) => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]);
// Example
partition([1, 2, 3, 4, 5], (n) => n % 2); // [[1, 3, 5], [2, 4]]
38.
Remove duplicate values in an array
#
const removeDuplicate = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
// Example
removeDuplicate(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); //  ['h', 'e', 'w', 'r', 'd']
39.
Remove falsy values from array
#
const removeFalsy = (arr) => arr.filter(Boolean);
// Example
removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]); // ['a string', true, 5, 'another string']
40.
Repeat an array
#
// `arr` is an array
const repeat = (arr, n) => [].concat(...Array(n).fill(arr));
// Or
const repeat = (arr, n) => Array(n).fill(arr).flat();
// Or
const repeat = (arr, n) =>
Array(arr.length * n)
.fill(0)
.map((_, i) => arr[i % arr.length]);
// Or
const repeat = (arr, n) => Array.from({ length: arr.length * n }, (_, i) => arr[i % arr.length]);
// Examples
repeat([1, 2, 3], 3); // [1, 2, 3, 1, 2, 3, 1, 2, 3]
41.
Shuffle an array
#
const shuffle = (arr) =>
arr
.map((a) => ({ sort: Math.random(), value: a }))
.sort((a, b) => a.sort - b.sort)
.map((a) => a.value);
// Or
const shuffle = (arr) => arr.sort(() => 0.5 - Math.random());
// Example
shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // [9, 1, 10, 6, 8, 5, 2, 3, 7, 4]
42.
Sort an array of items by given key
#
const sortBy = (arr, k) => arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0));
// Example
const people = [
{ name: 'Foo', age: 42 },
{ name: 'Bar', age: 24 },
{ name: 'Fuzz', age: 36 },
{ name: 'Baz', age: 32 },
];
sortBy(people, 'age');
// returns
// [
// { name: 'Bar', age: 24 },
// { name: 'Baz', age: 32 },
// { name: 'Fuzz', age: 36 },
// { name: 'Foo', age: 42 },
// ]
43.
Sort an array of numbers
#
const sort = (arr) => arr.sort((a, b) => a - b);
// Example
sort([1, 5, 2, 4, 3]); // [1, 2, 3, 4, 5]
44.
Split an array into chunks
#
const chunk = (arr, size) =>
arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []);
// Examples
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3); // [[1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 4); // [[1, 2, 3, 4], [5, 6, 7, 8]]
45.
Swap the rows and columns of a matrix
#
const transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i]));
// Or
const transpose = (matrix) => matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c]));
// Or
const transpose = (matrix) => matrix.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), []);
// Example
transpose([
// [
[1, 2, 3], // [1, 4, 7],
[4, 5, 6], // [2, 5, 8],
[7, 8, 9], // [3, 6, 9],
]); // ]
46.
Swap two array items
#
// `i` must be less than `j`
const swapItems = (a, i, j) =>
(a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)]) || a;
// Example
swapItems([1, 2, 3, 4, 5], 1, 4); // [1, 5, 3, 4, 2]
47.
Unzip an array of arrays
#
const unzip = (arr) =>
arr.reduce(
(acc, c) => (c.forEach((v, i) => acc[i].push(v)), acc),
Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_) => [])
);
// Example
unzip([
['a', 1],
['b', 2],
['c', 3],
['d', 4],
['e', 5],
]); // [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]]
/*
a 1
b 2
c 3
d 4
e 5
*/
48.
Zip multiple arrays
#
const zip = (...arr) => Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_, i) => arr.map((a) => a[i]));
// Example
zip(['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]); // [['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]
/*
Does it look like a zipper?
a 1
b 2
c 3
d 4
e 5
*/

Date Time

49.
Add AM PM suffix to an hour
#
// `h` is an hour number between 0 and 23
const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;
// Examples
suffixAmPm(0); // '12am'
suffixAmPm(5); // '5am'
suffixAmPm(12); // '12pm'
suffixAmPm(15); // '3pm'
suffixAmPm(23); // '11pm'
50.
Calculate the number of difference days between two dates
#
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
// Example
diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839
51.
Calculate the number of months between two dates
#
const monthDiff = (startDate, endDate) =>
Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
// Example
monthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12
52.
Compare two dates
#
// `a` and `b` are `Date` instances
const compare = (a, b) => a.getTime() > b.getTime();
// Example
compare(new Date('2020-03-30'), new Date('2020-01-01')); // true
53.
Convert a date to YYYY-MM-DD format
#
// `date` is a `Date` object
const formatYmd = (date) => date.toISOString().slice(0, 10);
// Example
formatYmd(new Date()); // 2020-05-06
54.
Convert seconds to hh:mm:ss format
#
// `s` is number of seconds
const formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8);
// Or
const formatSeconds = (s) => new Date(s * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
// Or
const formatSeconds = (s) =>
[parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(':').replace(/\b(\d)\b/g, '0$1');
// Examples
formatSeconds(200); // 00:03:20
formatSeconds(500); // 00:08:20
55.
Extract year, month, day, hour, minute, second and millisecond from a date
#
// `date` is a `Date` object
const extract = (date) =>
date
.toISOString()
.split(/[^0-9]/)
.slice(0, -1);
// `extract` is an array of [year, month, day, hour, minute, second, millisecond]
56.
Format a date for the given locale
#
// `date` is a `Date` object
// `locale` is a locale (en-US, pt-BR, for example)
const format = (date, locale) => new Intl.DateTimeFormat(locale).format(date);
// Example
format(new Date(), 'pt-BR'); // 06/05/2020
57.
Get the current quarter of a date
#
const getQuarter = (d = new Date()) => Math.ceil((d.getMonth() + 1) / 3);
58.
Get the current timestamp in seconds
#
const ts = () => Math.floor(new Date().getTime() / 1000);
59.
Get the day of the year from a date
#
// `date` is a Date object
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));
// Example
dayOfYear(new Date(2020, 04, 16)); // 137
60.
Get the first date in the month of a date
#
const getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1);
61.
Get the last date in the month of a date
#
const getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() + 1, 0);
62.
Get the month name of a date
#
// `date` is a Date object
const getMonthName = (date) =>
[
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
' November',
'December',
][date.getMonth()];
63.
Get the number of days in given month
#
// `month` is zero-based index
const daysInMonth = (month, year) => new Date(year, month, 0).getDate();
64.
Get the timezone string
#
const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
// Example
getTimezone(); // 'Asia/Saigon'
65.
Get the tomorrow date
#
const tomorrow = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date());
// Or
const tomorrow = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24);
66.
Get the total number of days in a year
#
const numberOfDays = (year) => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);
// Or
const numberOfDays = (year) => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);
67.
Get the weekday of a date
#
// `date` is a Date object
const getWeekday = (date) =>
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
68.
Get the yesterday date
#
const yesterday = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());
// Or
const yesterday = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);
69.
Initialize the current date but set time to midnight
#
const midnightOfToday = () => new Date(new Date().setHours(0, 0, 0, 0));
70.
Sort an array of dates
#
// `arr` is an array of `Date` items
const sortDescending = (arr) => arr.sort((a, b) => a.getTime() > b.getTime());
const sortAscending = (arr) => arr.sort((a, b) => a.getTime() < b.getTime());

DOM

71.
Check if an element is a descendant of another
#
const isDescendant = (child, parent) => parent.contains(child);
72.
Check if an element is focused
#
const hasFocus = (ele) => ele === document.activeElement;
73.
Check if the touch events are supported
#
const touchSupported = () =>
'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);
74.
Check if user scrolls to the bottom of the page
#
const isAtBottom = () =>
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
75.
Detect Internet Explorer browser
#
const isIE = !!document.documentMode;
76.
Detect macOS browser
#
const isMacBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
77.
Get all siblings of an element
#
const siblings = (ele) => [].slice.call(ele.parentNode.children).filter((child) => child !== ele);
78.
Get the position of an element relative to the document
#
const getPosition = (ele) => (
(r = ele.getBoundingClientRect()), { left: r.left + window.scrollX, top: r.top + window.scrollY }
);
// Example
getPosition(document.body); // { left: 0, top: 0 }
79.
Get the selected text
#
const getSelectedText = () => window.getSelection().toString();
80.
Go back to the previous page
#
history.back();
// Or
history.go(-1);
81.
Hide an element
#
// Pick the method that is suitable for your use case
const hide = (ele) => (ele.style.display = 'none');
// Or
const hide = (ele) => (ele.style.visibility = 'hidden');
// Or
const hide = (ele) => (ele.hidden = true);
82.
Insert an element after other one
#
const insertAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling);
// Or
const insertAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele);
83.
Insert an element before other one
#
const insertBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle);
// Or
const insertBefore = (ele, anotherEle) => anotherEle.insertAdjacentElement('beforebegin', ele);
84.
Insert given HTML after an element
#
const insertHtmlAfter = (html, ele) => ele.insertAdjacentHTML('afterend', html);
85.
Insert given HTML before an element
#
const insertHtmlBefore = (html, ele) => ele.insertAdjacentHTML('beforebegin', html);
86.
Redirect to another page
#
const goTo = (url) => (location.href = url);
87.
Reload the current page
#
const reload = () => location.reload();
// Or
const reload = () => (location.href = location.href);
88.
Replace an element
#
const replace = (ele, newEle) => ele.parentNode.replaceChild(newEle, ele);
89.
Scroll to top of the page
#
const goToTop = () => window.scrollTo(0, 0);
90.
Serialize form data
#
const serialize = (formEle) =>
Array.from(new FormData(formEle)).reduce(
(p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),
{}
);
91.
Show an element
#
const show = (ele) => (ele.style.display = '');
92.
Strip HTML from a given text
#
const stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || '';
93.
Toggle an element
#
const toggle = (ele) => (ele.style.display = ele.style.display === 'none' ? 'block' : 'none');
// Or
const toggle = (ele) => (ele.hidden = !ele.hidden);

Function

94.
Box handler
#
const boxHandler = (x) => ({ next: (f) => boxHandler(f(x)), done: (f) => f(x) });
// Example 1
const getPercentNumber = (str) =>
boxHandler(str)
.next((str) => str.replace(/\%/, ''))
.next((str) => parseFloat(str))
.done((res) => res * 0.01);
getPercentNumber('50%'); // 0.5
// Example 2
const getMoney = (price) => Number.parseFloat(price.replace(/\$/, ''));
const getPercent = (percent) => Number.parseFloat(percent.replace(/\%/)) * 0.01;
const getDiscountPrice = (price, discount) =>
boxHandler(getMoney(price))
.done((cents) => boxHandler(getPercent(discount)).next((save) => cents - cents * save))
.done((res) => res);
getDiscountPrice('$6.00', '20%'); // 4.8
95.
Check if a value is a function
#
const isFunction = (v) =>
['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes(
Object.prototype.toString.call(v)
);
// Examples
isFunction(function () {}); // true
isFunction(function* () {}); // true
isFunction(async function () {}); // true
96.
Check if a value is a generator function
#
const isGeneratorFunction = (v) => Object.prototype.toString.call(v) === '[object GeneratorFunction]';
// Examples
isGeneratorFunction(function () {}); // false
isGeneratorFunction(function* () {}); // true
97.
Check if a value is an async function
#
const isAsyncFunction = (v) => Object.prototype.toString.call(v) === '[object AsyncFunction]';
// Examples
isAsyncFunction(function () {}); // false
isAsyncFunction(function* () {}); // false
isAsyncFunction(async function () {}); // true
98.
Compose functions from left to right
#
// Compose functions from left to right
const pipe =
(...fns) =>
(x) =>
fns.reduce((y, f) => f(y), x);
// Example
const lowercase = (str) => str.toLowerCase();
const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
const reverse = (str) => str.split('').reverse().join('');
const fn = pipe(lowercase, capitalize, reverse);
// We will execute `lowercase`, `capitalize` and `reverse` in order
fn('Hello World') === 'dlrow olleH';
99.
Compose functions
#
// Compose functions from right to left
const compose =
(...fns) =>
(x) =>
fns.reduceRight((y, f) => f(y), x);
// Example
const lowercase = (str) => str.toLowerCase();
const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
const reverse = (str) => str.split('').reverse().join('');
const fn = compose(reverse, capitalize, lowercase);
// We will execute `lowercase`, `capitalize` and `reverse` in order
fn('Hello World') === 'dlrow olleH';
100.
Create a function that accepts a single argument
#
const unary = (fn) => (arg) => fn(arg);
// Example
['1', '2', '3', '4', '5'].map(unary(parseInt)); // [1, 2, 3, 4, 5]
101.
Create an empty function
#
const noop = () => {};
// Or
const noop = Function();
// calling Function() might be detected as using eval by some security tools
102.
Curry a function
#
const curry = (fn, ...args) => (fn.length <= args.length ? fn(...args) : curry.bind(null, fn, ...args));
// Example
const sum = (a, b, c) => a + b + c;
curry(sum)(1)(2)(3); // 6
curry(sum)(1, 2, 3); // 6
curry(sum, 1)(2, 3); // 6
curry(sum, 1)(2)(3); // 6
curry(sum, 1, 2)(3); // 6
curry(sum, 1, 2, 3); // 6
103.
Delay the evaluation of a function
#
// returns a new version of `fn` that returns values as lazy evaluable
const thunkfy =
(fn) =>
(...args) =>
() =>
fn(...args);
// Example
const heavyComputation = (x) => doStuff(x);
const unnecessarySlow = manyThings.map(heavyComputation).find((result) => result.criteria);
const probablyFaster = manyThings.map(thunkfy(heavyComputation)).find((thunk) => thunk().criteria);
104.
Execute a function once
#
const once = (fn) =>
(
(ran = false) =>
() =>
ran ? fn : ((ran = !ran), (fn = fn()))
)();
// Example
let n = 0;
const incOnce = once(() => ++n);
incOnce(); // n = 1
incOnce(); // n = 1
incOnce(); // n = 1
105.
Flip the arguments of a function
#
// Reverse the order of arguments
const flip =
(fn) =>
(...args) =>
fn(...args.reverse());
// For binary functions
const flip = (fn) => (b, a) => fn(a, b);
// Or for curried functions
const flip = (fn) => (b) => (a) => fn(a)(b);
// Example
const isParent = (parent, child) => parent.children.includes(child);
const isChild = flip(isParent);
106.
Identity function
#
const identity = (x) => x;
107.
Logical xor operator
#
// returns `true` if one of the arguments is truthy and the other is falsy
const xor = (a, b) => (a && !b) || (!a && b);
// Or
const xor = (a, b) => !(!a && !b) && !(a && b);
// Or
const xor = (a, b) => Boolean(!a ^ !b);
// Examples
xor(true, true); // false
xor(false, false); // false
xor(true, false); // true
xor(false, true); // true
108.
Memoize a function
#
const memoize = (fn) =>
(
(cache = {}) =>
(arg) =>
cache[arg] || (cache[arg] = fn(arg))
)();
// Example
// Calculate Fibonacci numbers
const fibo = memoize((n) => (n <= 2 ? 1 : fibo(n - 1) + fibo(n - 2)));
fibo(1); // 1
fibo(2); // 1
fibo(3); // 2
fibo(4); // 3
fibo(5); // 5
fibo(6); // 8
109.
Partially apply a function
#
const partial =
(fn, ...a) =>
(...b) =>
fn(...a, ...b);
// Example
const sum = (x, y) => x + y;
const inc = partial(sum, 1);
inc(9); // 10
110.
Uncurry a function
#
// `fn` is a curried function
// `n` is the depth of parameters
const uncurry =
(fn, n = 1) =>
(...args) =>
(
(acc) => (args) =>
args.reduce((x, y) => x(y), acc)
)(fn)(args.slice(0, n));
// Example
const sum = (a) => (b) => (c) => a + b + c;
uncurry(sum, 1)(1)(2)(3); // 6
uncurry(sum, 2)(1, 2)(3); // 6
uncurry(sum, 3)(1, 2, 3); // 6

Math

111.
Calculate the angle of a line defined by two points
#
// In radians
const radiansAngle = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x);
// In degrees
const degreesAngle = (p1, p2) => (Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180) / Math.PI;
112.
Calculate the distance between two points
#
const distance = (p1, p2) => Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
113.
Calculate the linear interpolation between two numbers
#
const lerp = (a, b, amount) => (1 - amount) * a + amount * b;
114.
Calculate the midpoint between two points
#
const midpoint = (p1, p2) => [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2];
115.
Check if a point is inside a rectangle
#
const isInside = (point, rect) =>
point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom;
116.
Check if a rectangle contains other one
#
// Returns true if `a` contains `b`
// (x1, y1) and (x2, y2) are top-left and bottom-right corners
const contains = (a, b) => a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2;
117.
Check if a rectangle overlaps other one
#
// Returns true if `a` overlaps `b`
// (x1, y1) and (x2, y2) are top-left and bottom-right corners
const overlaps = (a, b) => (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2);
118.
Convert degrees to radians
#
const degsToRads = (deg) => (deg * Math.PI) / 180.0;
119.
Convert radians to degrees
#
const radsToDegs = (rad) => (rad * 180) / Math.PI;
120.
Normalize the ratio of a number in a range
#
const normalizeRatio = (value, min, max) => (value - min) / (max - min);
121.
Round a number to the nearest multiple of a given value
#
const roundNearest = (value, nearest) => Math.round(value / nearest) * nearest;
// Examples
roundNearest(100, 30); // 90
roundNearest(200, 30); // 210
roundNearest(200, 40); // 200

Misc

122.
Check if the code is running in NodeJS
#
const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
123.
Check if the code is running in the browser
#
const isBrowser = typeof window === 'object' && typeof document === 'object';
124.
Clear all cookies
#
const clearCookies = () =>
document.cookie
.split(';')
.forEach(
(c) =>
(document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`))
);
// Example
clearCookies();
125.
Convert 3 digits color to 6 digits color
#
const toFullHexColor = (color) =>
`#${(color.startsWith('#') ? color.slice(1) : color)
.split('')
.map((c) => `${c}${c}`)
.join('')}`;
// Example
toFullHexColor('123'); // '#112233'
toFullHexColor('#123'); // '#112233'
toFullHexColor('#abc'); // '#aabbcc'
126.
Convert Celsius to Fahrenheit
#
const celsiusToFahrenheit = (celsius) => (celsius * 9) / 5 + 32;
// Examples
celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(0); // 32
celsiusToFahrenheit(-20); // -4
127.
Convert cookie to object
#
const cookies = document.cookie
.split(';')
.map((item) => item.split('='))
.reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});
128.
Convert Fahrenheit to Celsius
#
const fahrenheitToCelsius = (fahrenheit) => ((fahrenheit - 32) * 5) / 9;
// Examples
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0
129.
Convert hex to rgb
#
const hexToRgb = (hex) =>
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((x) => parseInt(x, 16));
// Examples
hexToRgb('#00ffff'); // [0, 255, 255]
hexToRgb('#0ff'); // [0, 255, 255]
130.
Convert rgb color to hex
#
const rgbToHex = (red, green, blue) => `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`;
// Or
const rgbToHex = (red, green, blue) => `#${[red, green, blue].map((v) => v.toString(16).padStart(2, '0')).join('')}`;
// Example
rgbToHex(0, 255, 255); // '#00ffff'
131.
Convert URL parameters to object
#
const getUrlParams = (query) =>
Array.from(new URLSearchParams(query)).reduce(
(p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),
{}
);
// Examples
getUrlParams(location.search); // Get the parameters of the current URL
getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }
// Duplicate key
getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }
132.
Decode a JWT token
#
const decode = (token) =>
decodeURIComponent(
atob(token.split('.')[1].replace('-', '+').replace('_', '/'))
.split('')
.map((c) => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`)
.join('')
);
// Example
decode(`
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0I
joxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
`);
// { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
133.
Detect dark mode
#
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
134.
Easing functions
#
// Some easing functions
// See https://gist.github.com/gre/1650294 and https://easings.net
const linear = (t) => t;
const easeInQuad = (t) => t * t;
const easeOutQuad = (t) => t * (2 - t);
const easeInOutQuad = (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t);
const easeInCubic = (t) => t * t * t;
const easeOutCubic = (t) => --t * t * t + 1;
const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1);
const easeInQuart = (t) => t * t * t * t;
const easeOutQuart = (t) => 1 - --t * t * t * t;
const easeInOutQuart = (t) => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t);
const easeInQuint = (t) => t * t * t * t * t;
const easeOutQuint = (t) => 1 + --t * t * t * t * t;
const easeInOutQuint = (t) => (t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t);
const easeInSine = (t) => 1 + Math.sin((Math.PI / 2) * t - Math.PI / 2);
const easeOutSine = (t) => Math.sin((Math.PI / 2) * t);
const easeInOutSine = (t) => (1 + Math.sin(Math.PI * t - Math.PI / 2)) / 2;
const easeInElastic = (t) => (0.04 - 0.04 / t) * Math.sin(25 * t) + 1;
const easeOutElastic = (t) => ((0.04 * t) / --t) * Math.sin(25 * t);
const easeInOutElastic = (t) =>
(t -= 0.5) < 0 ? (0.02 + 0.01 / t) * Math.sin(50 * t) : (0.02 - 0.01 / t) * Math.sin(50 * t) + 1;
135.
Emulate a dice throw
#
const throwdice = () => ~~(Math.random() * 6) + 1;
// Examples
throwdice(); // 4
throwdice(); // 1
throwdice(); // 6
136.
Encode a URL
#
// `encodeURIComponent` doesn't encode -_.!~*'()
const encode = (url) =>
encodeURIComponent(url)
.replace(/!/g, '%21')
.replace(/~/g, '%7E')
.replace(/\*/g, '%2A')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/%20/g, '+');
137.
Generate an unique and increment id
#
const uid = (() => ((id = 0), () => id++))();
// Examples
uid(); // 0
uid(); // 1
uid(); // 2
uid(); // 3
138.
Get the first defined and non null argument
#
const coalesce = (...args) => args.find((item) => item !== undefined && item !== null);
// Or
const coalesce = (...args) => args.find((item) => ![undefined, null].includes(item));
// Examples
coalesce(undefined, null, 'helloworld', NaN); // 'helloworld'
139.
Get the value of a cookie
#
const cookie = (name) => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
// Example
cookie('_ga'); // GA1.2.825309271.1581874719
140.
Get the value of a param from a URL
#
const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param);
// Example
getParam('http://domain.com?message=hello', 'message'); // 'hello'
141.
Get type of a variable in string
#
const getTypeOf = (obj) => Object.prototype.toString.call(obj).match(/\[object (.*)\]/)[1];
// Examples
getTypeOf('hello world'); // String
getTypeOf(1000); // Number
getTypeOf(Infinity); // Number
getTypeOf(true); // Boolean
getTypeOf(Symbol()); // Symbol
getTypeOf(null); // Null
getTypeOf(undefined); // Undefined
getTypeOf({}); // Object
getTypeOf([]); // Array
getTypeOf(/[a-z]/g); // RegExp
getTypeOf(new Date(2021)); // Date
getTypeOf(new Error()); // Error
getTypeOf(function () {}); // Function
getTypeOf((a, b) => a + b); // Function
getTypeOf(async () => {}); // AsyncFunction
getTypeOf(document); // HTMLDocument
142.
Redirect the page to HTTPS if it is in HTTP
#
const redirectHttps = () =>
location.protocol === 'https:' ? {} : location.replace(`https://${location.href.split('//')[1]}`);
// Or
const redirectHttps = () => (location.protocol === 'https:' ? {} : (location.protocol = 'https:'));
143.
Run Promises in sequence
#
// `promises` is an array of `Promise`
const run = (promises) => promises.reduce((p, c) => p.then((rp) => c.then((rc) => [...rp, rc])), Promise.resolve([]));
// Example
run(promises).then((results) => {
// `results` is an array of promise results in the same order
});
144.
Swap two variables
#
[a, b] = [b, a];
// Or
a = [b, (b = a)][0];
// Or
a = ((x) => x)(b, (b = a));
// Or
// (only works with numbers)
a = b + ((b = a), 0);
a = b * ((b = a), 1);
145.
Wait for an amount of time
#
const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));

Number

146.
Add an ordinal suffix to a number
#
// `n` is a position number
const addOrdinal = (n) => `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`;
// Or
const addOrdinal = (n) => `${n}${[, 'st', 'nd', 'rd'][/1?.$/.exec(n)] || 'th'}`;
// Or
const addOrdinal = (n) => `${n}${[, 'st', 'nd', 'rd'][(n % 100 >> 3) ^ 1 && n % 10] || 'th'}`;
// Or
const addOrdinal = (n) =>
`${n}${
{ one: 'st', two: 'nd', few: 'rd', other: 'th' }[new Intl.PluralRules('en', { type: 'ordinal' }).select(n)]
}`;
// Examples
addOrdinal(1); // '1st'
addOrdinal(2); // '2nd'
addOrdinal(3); // '3rd'
addOrdinal(11); // '11th'
addOrdinal(12); // '13th'
addOrdinal(13); // '13th'
147.
Calculate Fibonacci numbers
#
const fibo = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = fibo(n - 1, memo) + fibo(n - 2, memo)));
// Examples
fibo(1); // 1
fibo(2); // 1
fibo(3); // 2
fibo(4); // 3
fibo(5); // 5
fibo(6); // 8
148.
Calculate the average of arguments
#
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
// Example
average(1, 2, 3, 4); // 2.5
149.
Calculate the division of arguments
#
const division = (...args) => args.reduce((a, b) => a / b);
// Example
division(1, 2, 3, 4); // 0.04166666666666666
150.
Calculate the factorial of a number
#
const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));
// Examples
factorial(2); // 2
factorial(3); // 6
factorial(4); // 24
factorial(5); // 120
factorial(6); // 720
151.
Calculate the mod of collection index
#
const mod = (a, b) => ((a % b) + b) % b;
// Examples
mod(-1, 5); // 4
mod(3, 5); // 3
mod(6, 5); // 1
152.
Calculate the remainder of division of arguments
#
const remainder = (...args) => args.reduce((a, b) => a % b);
// Example
remainder(1, 2, 3, 4); // 1
153.
Calculate the sum of arguments
#
const sum = (...args) => args.reduce((a, b) => a + b);
// Example
sum(1, 2, 3, 4); // 10
154.
Clamp a number between two values
#
const clamp = (val, min = 0, max = 1) => Math.max(min, Math.min(max, val));
// Example
clamp(199, 10, 25); // 25
155.
Compute the greatest common divisor between two numbers
#
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
// Example
gcd(10, 15); // 5
156.
Convert a number to equivalent characters
#
const toChars = (n) => `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`;
// Examples
toChars(0); // A
toChars(1); // B
toChars(25); // Z
toChars(26); // AA
toChars(27); // AB
toChars(51); // AZ
toChars(701); // ZZ
toChars(702); // AAA
toChars(703); // AAB
157.
Convert a string to number
#
const toNumber = (str) => +str;
// Example
toNumber('42'); // 42
158.
Convert decimal to binary recursively
#
const decToBi = (num) => (num === 0 ? 0 : (num % 2) + 10 * decToBi(~~(num / 2)));
// Example
decToBi(10); //1010
159.
Get the arrays of digits from a number
#
const digitize = (n) => `${n}`.split('').map((v) => parseInt(v, 10));
// Or
const digitize = (n) => [...`${n}`].map((v) => parseInt(v, 10));
// Example
digitize(123); // [1, 2, 3]
160.
Multiply arguments
#
const mul = (...args) => args.reduce((a, b) => a * b);
// Example
mul(1, 2, 3, 4); // 24
161.
Prefix an integer with zeros
#
const prefixWithZeros = (number, length) => (number / Math.pow(10, length)).toFixed(length).substr(2);
// Or
const prefixWithZeros = (number, length) => `${Array(length).join('0')}${number}`.slice(-length);
// Or
const prefixWithZeros = (number, length) => String(number).padStart(length, '0');
// Example
prefixWithZeros(42, 5); // '00042'
162.
Round a number to a given number of digits
#
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
// Examples
round(1.234567, 3); // 1.235
round(1.234567, 4); // 1.2346
163.
Subtract arguments
#
const subtract = (...args) => args.reduce((a, b) => a - b);
// Example
subtract(1, 2, 3, 4); // -8
164.
Truncate a number at decimal
#
const truncate = (n) => ~~n;
// Examples
truncate(25.198726354); // 25
truncate(-25.198726354); // -25
165.
Truncate a number to a given number of decimal places without rounding
#
const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\\d+(?:\.\\d{0,${fixed}})?`))[0];
// Or
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed