const castArray = (value) => (Array.isArray(value) ? value : [value]);// ExamplescastArray(1); // [1]castArray([1, 2, 3]); // [1, 2, 3]
// `arr` is an arrayconst isEmpty = (arr) => !Array.isArray(arr) || arr.length === 0;// ExamplesisEmpty([]); // trueisEmpty([1, 2, 3]); // false
// `arr` is an arrayconst clone = (arr) => arr.slice(0);// Orconst clone = (arr) => [...arr];// Orconst clone = (arr) => Array.from(arr);// Orconst clone = (arr) => arr.map((x) => x);// Orconst clone = (arr) => JSON.parse(JSON.stringify(arr));// Orconst clone = (arr) => arr.concat([]);
// `a` and `b` are arraysconst isEqual = (a, b) => JSON.stringify(a.sort()) === JSON.stringify(b.sort());// ExamplesisEqual([1, 2, 3], [1, 2, 3]); // trueisEqual([1, 2, 3], [1, 3, 2]); // trueisEqual([1, 2, 3], [1, '2', 3]); // false
// `a` and `b` are arraysconst isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);// Orconst isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);// ExamplesisEqual([1, 2, 3], [1, 2, 3]); // trueisEqual([1, 2, 3], [1, '2', 3]); // false
const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});// Orconst toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it]));// ExampletoObject([{ 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' },}*/
const toNumbers = (arr) => arr.map(Number);// Orconst toNumbers = (arr) => arr.map((x) => +x);// ExampletoNumbers(['2', '3', '4']); // [2, 3, 4]
const countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {});// ExamplecountBy([{ 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 }
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);// Orconst countOccurrences = (arr, val) => arr.filter((item) => item === val).length;// ExamplescountOccurrences([2, 1, 3, 3, 2, 3], 2); // 2countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a'); // 3
const countOccurrences = (arr) => arr.reduce((prev, curr) => ((prev[curr] = ++prev[curr] || 1), prev), {});// ExamplescountOccurrences([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 }
const accumulate = (arr) =>arr.map(((sum) => (value) =>(sum += value))(0));// Orconst accumulate = (arr) => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), []);// Orconst accumulate = (arr) => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), 0);// Exampleaccumulate([1, 2, 3, 4]); // [1, 3, 6, 10]// 1 = 1// 1 + 2 = 3// 1 + 2 + 3 = 6// 1 + 2 + 3 + 4 = 10
const range = (min, max) => [...Array(max - min + 1).keys()].map((i) => i + min);// Orconst range = (min, max) =>Array(max - min + 1).fill(0).map((_, i) => min + i);// Orconst range = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i);// Examplerange(5, 10); // [5, 6, 7, 8, 9, 10]
const cartesian = (...sets) => sets.reduce((acc, set) => acc.flatMap((x) => set.map((y) => [...x, y])), [[]]);// Examplecartesian([1, 2], [3, 4]); // [ [1, 3], [1, 4], [2, 3], [2, 4] ]/*3 4---------------1 | [1, 3] [1, 4]|2 | [2, 3] [2, 4]*/
const empty = (arr) => (arr.length = 0);// Orarr = [];
// 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));// Orconst closest = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0];// Exampleclosest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33
const lastIndex = (arr, predicate) => arr.reduce((prev, curr, index) => (predicate(curr) ? index : prev), -1);// Orconst lastIndex = (arr, predicate) => arr.map((item) => predicate(item)).lastIndexOf(true);// ExamplelastIndex([1, 3, 5, 7, 9, 2, 4, 6, 8], (i) => i % 2 === 1); // 4lastIndex([1, 3, 5, 7, 9, 8, 6, 4, 2], (i) => i > 6); // 5
const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);// ExamplesindexOfMax([1, 3, 9, 7, 5]); // 2indexOfMax([1, 3, 7, 7, 5]); // 2
const indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0);// ExamplesindexOfMin([6, 4, 8, 2, 10]); // 3indexOfMin([6, 4, 2, 2, 10]); // 2
const findLongest = (words) => Math.max(...words.map((el) => el.length));// ExamplefindLongest(['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']); // 6
const maxBy = (arr, key) => arr.reduce((a, b) => (a[key] >= b[key] ? a : b), {});// Exampleconst people = [{ name: 'Bar', age: 24 },{ name: 'Baz', age: 32 },{ name: 'Foo', age: 42 },{ name: 'Fuzz', age: 36 },];maxBy(people, 'age'); // { name: 'Foo', age: 42 }
const max = (arr) => Math.max(...arr);
const minBy = (arr, key) => arr.reduce((a, b) => (a[key] < b[key] ? a : b), {});// Exampleconst people = [{ name: 'Bar', age: 24 },{ name: 'Baz', age: 32 },{ name: 'Foo', age: 42 },{ name: 'Fuzz', age: 36 },];minBy(people, 'age'); // { name: 'Bar', age: 24 }
const min = (arr) => Math.min(...arr);
const flat = (arr) =>[].concat.apply([],arr.map((a) => (Array.isArray(a) ? flat(a) : a)));// Orconst 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-flatconst flat = (arr) => arr.flat();// Exampleflat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger']
const getConsecutiveArrays = (arr, size) =>size > arr.length ? [] : arr.slice(size - 1).map((_, i) => arr.slice(i, size + i));// ExamplesgetConsecutiveArrays([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); // []
const getNthItems = (arr, nth) => arr.filter((_, i) => i % nth === nth - 1);// ExamplesgetNthItems([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]
const getSubsets = (arr) => arr.reduce((prev, curr) => prev.concat(prev.map((k) => k.concat(curr))), [[]]);// ExamplesgetSubsets([1, 2]); // [[], [1], [2], [1, 2]]getSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
const indices = (arr, value) => arr.reduce((acc, v, i) => (v === value ? [...acc, i] : acc), []);// Orconst indices = (arr, value) => arr.map((v, i) => (v === value ? i : false)).filter(Boolean);// Examplesindices(['h', 'e', 'l', 'l', 'o'], 'l'); // [2, 3]indices(['h', 'e', 'l', 'l', 'o'], 'w'); // []
const average = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
const getIntersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)));// ExamplesgetIntersection([1, 2, 3], [2, 3, 4, 5]); // [2, 3]getIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]); // [3]
const ranking = (arr) => arr.map((x, y, z) => z.filter((w) => w > x).length + 1);// Examplesranking([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]
const sum = (arr) => arr.reduce((a, b) => a + b, 0);
const unique = (arr) => [...new Set(arr)];// Orconst unique = (arr) => arr.filter((el, i, array) => array.indexOf(el) === i);// Orconst unique = (arr) => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), []);
const union = (...arr) => [...new Set(arr.flat())];// Exampleunion([1, 2], [2, 3], [3]); // [1, 2, 3]
const groupBy = (arr, key) =>arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {});// ExamplegroupBy([{ 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' }],}*/
// Merge but don't remove the duplicationsconst merge = (a, b) => a.concat(b);// Orconst merge = (a, b) => [...a, ...b];// Merge and remove the duplicationsconst merge = [...new Set(a.concat(b))];// Orconst merge = [...new Set([...a, ...b])];
const partition = (arr, criteria) => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]);// Examplepartition([1, 2, 3, 4, 5], (n) => n % 2); // [[1, 3, 5], [2, 4]]
const removeDuplicate = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));// ExampleremoveDuplicate(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); // ['h', 'e', 'w', 'r', 'd']
const removeFalsy = (arr) => arr.filter(Boolean);// ExampleremoveFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false]); // ['a string', true, 5, 'another string']
// `arr` is an arrayconst repeat = (arr, n) => [].concat(...Array(n).fill(arr));// Orconst repeat = (arr, n) => Array(n).fill(arr).flat();// Orconst repeat = (arr, n) =>Array(arr.length * n).fill(0).map((_, i) => arr[i % arr.length]);// Orconst repeat = (arr, n) => Array.from({ length: arr.length * n }, (_, i) => arr[i % arr.length]);// Examplesrepeat([1, 2, 3], 3); // [1, 2, 3, 1, 2, 3, 1, 2, 3]
const shuffle = (arr) =>arr.map((a) => ({ sort: Math.random(), value: a })).sort((a, b) => a.sort - b.sort).map((a) => a.value);// Orconst shuffle = (arr) => arr.sort(() => 0.5 - Math.random());// Exampleshuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // [9, 1, 10, 6, 8, 5, 2, 3, 7, 4]
const sortBy = (arr, k) => arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0));// Exampleconst 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 },// ]
const sort = (arr) => arr.sort((a, b) => a - b);// Examplesort([1, 5, 2, 4, 3]); // [1, 2, 3, 4, 5]
const chunk = (arr, size) =>arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []);// Exampleschunk([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]]
const transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i]));// Orconst transpose = (matrix) => matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c]));// Orconst transpose = (matrix) => matrix.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), []);// Exampletranspose([// [[1, 2, 3], // [1, 4, 7],[4, 5, 6], // [2, 5, 8],[7, 8, 9], // [3, 6, 9],]); // ]
// `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;// ExampleswapItems([1, 2, 3, 4, 5], 1, 4); // [1, 5, 3, 4, 2]
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)) }, (_) => []));// Exampleunzip([['a', 1],['b', 2],['c', 3],['d', 4],['e', 5],]); // [['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]]/*a 1b 2c 3d 4e 5*/
const zip = (...arr) => Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_, i) => arr.map((a) => a[i]));// Examplezip(['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 1b 2c 3d 4e 5*/
// `h` is an hour number between 0 and 23const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;// ExamplessuffixAmPm(0); // '12am'suffixAmPm(5); // '5am'suffixAmPm(12); // '12pm'suffixAmPm(15); // '3pm'suffixAmPm(23); // '11pm'
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));// ExamplediffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839
const monthDiff = (startDate, endDate) =>Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());// ExamplemonthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12
// `a` and `b` are `Date` instancesconst compare = (a, b) => a.getTime() > b.getTime();// Examplecompare(new Date('2020-03-30'), new Date('2020-01-01')); // true
// `date` is a `Date` objectconst formatYmd = (date) => date.toISOString().slice(0, 10);// ExampleformatYmd(new Date()); // 2020-05-06
// `s` is number of secondsconst formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8);// Orconst formatSeconds = (s) => new Date(s * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];// Orconst formatSeconds = (s) =>[parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(':').replace(/\b(\d)\b/g, '0$1');// ExamplesformatSeconds(200); // 00:03:20formatSeconds(500); // 00:08:20
// `date` is a `Date` objectconst extract = (date) =>date.toISOString().split(/[^0-9]/).slice(0, -1);// `extract` is an array of [year, month, day, hour, minute, second, millisecond]
// `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);// Exampleformat(new Date(), 'pt-BR'); // 06/05/2020
const getQuarter = (d = new Date()) => Math.ceil((d.getMonth() + 1) / 3);
const ts = () => Math.floor(new Date().getTime() / 1000);
// `date` is a Date objectconst dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));// ExampledayOfYear(new Date(2020, 04, 16)); // 137
const getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1);
const getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() + 1, 0);
// `date` is a Date objectconst getMonthName = (date) =>['January','February','March','April','May','June','July','August','September','October',' November','December',][date.getMonth()];
// `month` is zero-based indexconst daysInMonth = (month, year) => new Date(year, month, 0).getDate();
const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;// ExamplegetTimezone(); // 'Asia/Saigon'
const tomorrow = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date());// Orconst tomorrow = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24);
const numberOfDays = (year) => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);// Orconst numberOfDays = (year) => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);
// `date` is a Date objectconst getWeekday = (date) =>['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
const yesterday = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());// Orconst yesterday = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);
const midnightOfToday = () => new Date(new Date().setHours(0, 0, 0, 0));
// `arr` is an array of `Date` itemsconst sortDescending = (arr) => arr.sort((a, b) => a.getTime() > b.getTime());const sortAscending = (arr) => arr.sort((a, b) => a.getTime() < b.getTime());
const isDescendant = (child, parent) => parent.contains(child);
const hasFocus = (ele) => ele === document.activeElement;
const touchSupported = () =>'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);
const isAtBottom = () =>document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
const isIE = !!document.documentMode;
const isMacBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
const siblings = (ele) => [].slice.call(ele.parentNode.children).filter((child) => child !== ele);
const getPosition = (ele) => ((r = ele.getBoundingClientRect()), { left: r.left + window.scrollX, top: r.top + window.scrollY });// ExamplegetPosition(document.body); // { left: 0, top: 0 }
const getSelectedText = () => window.getSelection().toString();
history.back();// Orhistory.go(-1);
// Pick the method that is suitable for your use caseconst hide = (ele) => (ele.style.display = 'none');// Orconst hide = (ele) => (ele.style.visibility = 'hidden');// Orconst hide = (ele) => (ele.hidden = true);
const insertAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling);// Orconst insertAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele);
const insertBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle);// Orconst insertBefore = (ele, anotherEle) => anotherEle.insertAdjacentElement('beforebegin', ele);
const insertHtmlAfter = (html, ele) => ele.insertAdjacentHTML('afterend', html);
const insertHtmlBefore = (html, ele) => ele.insertAdjacentHTML('beforebegin', html);
const goTo = (url) => (location.href = url);
const reload = () => location.reload();// Orconst reload = () => (location.href = location.href);
const replace = (ele, newEle) => ele.parentNode.replaceChild(newEle, ele);
const goToTop = () => window.scrollTo(0, 0);
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 }),{});
const show = (ele) => (ele.style.display = '');
const stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || '';
const toggle = (ele) => (ele.style.display = ele.style.display === 'none' ? 'block' : 'none');// Orconst toggle = (ele) => (ele.hidden = !ele.hidden);
const boxHandler = (x) => ({ next: (f) => boxHandler(f(x)), done: (f) => f(x) });// Example 1const getPercentNumber = (str) =>boxHandler(str).next((str) => str.replace(/\%/, '')).next((str) => parseFloat(str)).done((res) => res * 0.01);getPercentNumber('50%'); // 0.5// Example 2const 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
const isFunction = (v) =>['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes(Object.prototype.toString.call(v));// ExamplesisFunction(function () {}); // trueisFunction(function* () {}); // trueisFunction(async function () {}); // true
const isGeneratorFunction = (v) => Object.prototype.toString.call(v) === '[object GeneratorFunction]';// ExamplesisGeneratorFunction(function () {}); // falseisGeneratorFunction(function* () {}); // true
const isAsyncFunction = (v) => Object.prototype.toString.call(v) === '[object AsyncFunction]';// ExamplesisAsyncFunction(function () {}); // falseisAsyncFunction(function* () {}); // falseisAsyncFunction(async function () {}); // true
// Compose functions from left to rightconst pipe =(...fns) =>(x) =>fns.reduce((y, f) => f(y), x);// Exampleconst 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 orderfn('Hello World') === 'dlrow olleH';
// Compose functions from right to leftconst compose =(...fns) =>(x) =>fns.reduceRight((y, f) => f(y), x);// Exampleconst 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 orderfn('Hello World') === 'dlrow olleH';
const unary = (fn) => (arg) => fn(arg);// Example['1', '2', '3', '4', '5'].map(unary(parseInt)); // [1, 2, 3, 4, 5]
const noop = () => {};// Orconst noop = Function();// calling Function() might be detected as using eval by some security tools
const curry = (fn, ...args) => (fn.length <= args.length ? fn(...args) : curry.bind(null, fn, ...args));// Exampleconst sum = (a, b, c) => a + b + c;curry(sum)(1)(2)(3); // 6curry(sum)(1, 2, 3); // 6curry(sum, 1)(2, 3); // 6curry(sum, 1)(2)(3); // 6curry(sum, 1, 2)(3); // 6curry(sum, 1, 2, 3); // 6
// returns a new version of `fn` that returns values as lazy evaluableconst thunkfy =(fn) =>(...args) =>() =>fn(...args);// Exampleconst heavyComputation = (x) => doStuff(x);const unnecessarySlow = manyThings.map(heavyComputation).find((result) => result.criteria);const probablyFaster = manyThings.map(thunkfy(heavyComputation)).find((thunk) => thunk().criteria);
const once = (fn) =>((ran = false) =>() =>ran ? fn : ((ran = !ran), (fn = fn())))();// Examplelet n = 0;const incOnce = once(() => ++n);incOnce(); // n = 1incOnce(); // n = 1incOnce(); // n = 1
// Reverse the order of argumentsconst flip =(fn) =>(...args) =>fn(...args.reverse());// For binary functionsconst flip = (fn) => (b, a) => fn(a, b);// Or for curried functionsconst flip = (fn) => (b) => (a) => fn(a)(b);// Exampleconst isParent = (parent, child) => parent.children.includes(child);const isChild = flip(isParent);
const identity = (x) => x;
// returns `true` if one of the arguments is truthy and the other is falsyconst xor = (a, b) => (a && !b) || (!a && b);// Orconst xor = (a, b) => !(!a && !b) && !(a && b);// Orconst xor = (a, b) => Boolean(!a ^ !b);// Examplesxor(true, true); // falsexor(false, false); // falsexor(true, false); // truexor(false, true); // true
const memoize = (fn) =>((cache = Object.create(null)) =>(arg) =>cache[arg] || (cache[arg] = fn(arg)))();// Example// Calculate Fibonacci numbersconst fibo = memoize((n) => (n <= 2 ? 1 : fibo(n - 1) + fibo(n - 2)));fibo(1); // 1fibo(2); // 1fibo(3); // 2fibo(4); // 3fibo(5); // 5fibo(6); // 8
const partial =(fn, ...a) =>(...b) =>fn(...a, ...b);// Exampleconst sum = (x, y) => x + y;const inc = partial(sum, 1);inc(9); // 10
// `fn` is a curried function// `n` is the depth of parametersconst uncurry =(fn, n = 1) =>(...args) =>((acc) => (args) =>args.reduce((x, y) => x(y), acc))(fn)(args.slice(0, n));// Exampleconst sum = (a) => (b) => (c) => a + b + c;uncurry(sum, 1)(1)(2)(3); // 6uncurry(sum, 2)(1, 2)(3); // 6uncurry(sum, 3)(1, 2, 3); // 6
// In radiansconst radiansAngle = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x);// In degreesconst degreesAngle = (p1, p2) => (Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180) / Math.PI;
const distance = (p1, p2) => Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
const lerp = (a, b, amount) => (1 - amount) * a + amount * b;
const midpoint = (p1, p2) => [(p1.x + p2.x) / 2, (p1.y + p2.y) / 2];
const isInside = (point, rect) =>point.x > rect.left && point.x < rect.right && point.y > rect.top && point.y < rect.bottom;
// Returns true if `a` contains `b`// (x1, y1) and (x2, y2) are top-left and bottom-right cornersconst contains = (a, b) => a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2;
// Returns true if `a` overlaps `b`// (x1, y1) and (x2, y2) are top-left and bottom-right cornersconst overlaps = (a, b) => (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2);
const degsToRads = (deg) => (deg * Math.PI) / 180.0;
const radsToDegs = (rad) => (rad * 180) / Math.PI;
const normalizeRatio = (value, min, max) => (value - min) / (max - min);
const roundNearest = (value, nearest) => Math.round(value / nearest) * nearest;// ExamplesroundNearest(100, 30); // 90roundNearest(200, 30); // 210roundNearest(200, 40); // 200
const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
const isBrowser = typeof window === 'object' && typeof document === 'object';
const clearCookies = () =>document.cookie.split(';').forEach((c) =>(document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)));// ExampleclearCookies();
const toFullHexColor = (color) =>`#${(color.startsWith('#') ? color.slice(1) : color).split('').map((c) => `${c}${c}`).join('')}`;// ExampletoFullHexColor('123'); // '#112233'toFullHexColor('#123'); // '#112233'toFullHexColor('#abc'); // '#aabbcc'
const celsiusToFahrenheit = (celsius) => (celsius * 9) / 5 + 32;// ExamplescelsiusToFahrenheit(15); // 59celsiusToFahrenheit(0); // 32celsiusToFahrenheit(-20); // -4
const cookies = document.cookie.split(';').map((item) => item.split('=')).reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});
const fahrenheitToCelsius = (fahrenheit) => ((fahrenheit - 32) * 5) / 9;// ExamplesfahrenheitToCelsius(59); // 15fahrenheitToCelsius(32); // 0
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));// ExampleshexToRgb('#00ffff'); // [0, 255, 255]hexToRgb('#0ff'); // [0, 255, 255]
const rgbToHex = (red, green, blue) => `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`;// Orconst rgbToHex = (red, green, blue) => `#${[red, green, blue].map((v) => v.toString(16).padStart(2, '0')).join('')}`;// ExamplergbToHex(0, 255, 255); // '#00ffff'
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 }),{});// ExamplesgetUrlParams(location.search); // Get the parameters of the current URLgetUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }// Duplicate keygetUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }
const decode = (token) =>decodeURIComponent(atob(token.split('.')[1].replace('-', '+').replace('_', '/')).split('').map((c) => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`).join(''));// Exampledecode(`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c`);// { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
// Some easing functions// See https://gist.github.com/gre/1650294 and https://easings.netconst 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;
const throwdice = () => ~~(Math.random() * 6) + 1;// Examplesthrowdice(); // 4throwdice(); // 1throwdice(); // 6
// `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, '+');
const uid = (() => ((id = 0), () => id++))();// Examplesuid(); // 0uid(); // 1uid(); // 2uid(); // 3
const coalesce = (...args) => args.find((item) => item !== undefined && item !== null);// Orconst coalesce = (...args) => args.find((item) => ![undefined, null].includes(item));// Examplescoalesce(undefined, null, 'helloworld', NaN); // 'helloworld'
const cookie = (name) => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();// Examplecookie('_ga'); // GA1.2.825309271.1581874719
const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param);// ExamplegetParam('http://domain.com?message=hello', 'message'); // 'hello'
const getTypeOf = (obj) => Object.prototype.toString.call(obj).match(/\[object (.*)\]/)[1];// ExamplesgetTypeOf('hello world'); // StringgetTypeOf(1000); // NumbergetTypeOf(Infinity); // NumbergetTypeOf(true); // BooleangetTypeOf(Symbol()); // SymbolgetTypeOf(null); // NullgetTypeOf(undefined); // UndefinedgetTypeOf({}); // ObjectgetTypeOf([]); // ArraygetTypeOf(/[a-z]/g); // RegExpgetTypeOf(new Date(2021)); // DategetTypeOf(new Error()); // ErrorgetTypeOf(function () {}); // FunctiongetTypeOf((a, b) => a + b); // FunctiongetTypeOf(async () => {}); // AsyncFunctiongetTypeOf(document); // HTMLDocument
const redirectHttps = () =>location.protocol === 'https:' ? {} : location.replace(`https://${location.href.split('//')[1]}`);// Orconst redirectHttps = () => (location.protocol === 'https:' ? {} : (location.protocol = 'https:'));
// `promises` is an array of `Promise`const run = (promises) => promises.reduce((p, c) => p.then((rp) => c.then((rc) => [...rp, rc])), Promise.resolve([]));// Examplerun(promises).then((results) => {// `results` is an array of promise results in the same order});
[a, b] = [b, a];// Ora = [b, (b = a)][0];// Ora = ((x) => x)(b, (b = a));// Or// (only works with numbers)a = b + ((b = a), 0);a = b * ((b = a), 1);
const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
// `n` is a position numberconst addOrdinal = (n) => `${n}${['st', 'nd', 'rd'][((((n + 90) % 100) - 10) % 10) - 1] || 'th'}`;// Orconst addOrdinal = (n) => `${n}${[, 'st', 'nd', 'rd'][/1?.$/.exec(n)] || 'th'}`;// Orconst addOrdinal = (n) => `${n}${[, 'st', 'nd', 'rd'][(n % 100 >> 3) ^ 1 && n % 10] || 'th'}`;// Orconst addOrdinal = (n) =>`${n}${{ one: 'st', two: 'nd', few: 'rd', other: 'th' }[new Intl.PluralRules('en', { type: 'ordinal' }).select(n)]}`;// ExamplesaddOrdinal(1); // '1st'addOrdinal(2); // '2nd'addOrdinal(3); // '3rd'addOrdinal(11); // '11th'addOrdinal(12); // '13th'addOrdinal(13); // '13th'
const fibo = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = fibo(n - 1, memo) + fibo(n - 2, memo)));// Examplesfibo(1); // 1fibo(2); // 1fibo(3); // 2fibo(4); // 3fibo(5); // 5fibo(6); // 8
const average = (...args) => args.reduce((a, b) => a + b) / args.length;// Exampleaverage(1, 2, 3, 4); // 2.5
const division = (...args) => args.reduce((a, b) => a / b);// Exampledivision(1, 2, 3, 4); // 0.04166666666666666
const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));// Examplesfactorial(2); // 2factorial(3); // 6factorial(4); // 24factorial(5); // 120factorial(6); // 720
const mod = (a, b) => ((a % b) + b) % b;// Examplesmod(-1, 5); // 4mod(3, 5); // 3mod(6, 5); // 1
const remainder = (...args) => args.reduce((a, b) => a % b);// Exampleremainder(1, 2, 3, 4); // 1
const sum = (...args) => args.reduce((a, b) => a + b);// Examplesum(1, 2, 3, 4); // 10
const clamp = (val, min = 0, max = 1) => Math.max(min, Math.min(max, val));// Exampleclamp(199, 10, 25); // 25
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));// Examplegcd(10, 15); // 5
const toChars = (n) => `${n >= 26 ? toChars(Math.floor(n / 26) - 1) : ''}${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n % 26]}`;// ExamplestoChars(0); // AtoChars(1); // BtoChars(25); // ZtoChars(26); // AAtoChars(27); // ABtoChars(51); // AZtoChars(701); // ZZtoChars(702); // AAAtoChars(703); // AAB
const toNumber = (str) => +str;// ExampletoNumber('42'); // 42
const decToBi = (num) => (num === 0 ? 0 : (num % 2) + 10 * decToBi(~~(num / 2)));// ExampledecToBi(10); //1010
const digitize = (n) => `${n}`.split('').map((v) => parseInt(v, 10));// Orconst digitize = (n) => [...`${n}`].map((v) => parseInt(v, 10));// Exampledigitize(123); // [1, 2, 3]
const mul = (...args) => args.reduce((a, b) => a * b);// Examplemul(1, 2, 3, 4); // 24
const prefixWithZeros = (number, length) => (number / Math.pow(10, length)).toFixed(length).substr(2);// Orconst prefixWithZeros = (number, length) => `${Array(length).join('0')}${number}`.slice(-length);// Orconst prefixWithZeros = (number, length) => String(number).padStart(length, '0');// ExampleprefixWithZeros(42, 5); // '00042'
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);// Examplesround(1.234567, 3); // 1.235round(1.234567, 4); // 1.2346
const subtract = (...args) => args.reduce((a, b) => a - b);// Examplesubtract(1, 2, 3, 4); // -8
const truncate = (n) => ~~n;// Examplestruncate(25.198726354); // 25truncate(-25.198726354); // -25
const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\\d+(?:\.\\d{0,${fixed}})?`))[0];// Orconst toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);// ExamplestoFixed(25.198726354, 1); // 25.1toFixed(25.198726354, 2); // 25.19toFixed(25.198726354, 3); // 25.198toFixed(25.198726354, 4); // 25.1987toFixed(25.198726354, 5); // 25.19872toFixed(25.198726354, 6); // 25.198726
const isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));// ExamplesisEqual({ foo: 'bar' }, { foo: 'bar' }); // trueisEqual({ foo: 'bar' }, { bar: 'foo' }); // false
// `map` doesn't have any propertiesconst map = Object.create(null);// The following `map` has `__proto__` property// const map = {};
const toObj = (arr) => Object.fromEntries(arr);// Orconst toObj = (arr) => arr.reduce((a, c) => ((a[c[0]] = c[1]), a), {});// ExampletoObj([['a', 1],['b', 2],['c', 3],]); // { a: 1, b: 2, c: 3 }
const pluck = (objs, property) => objs.map((obj) => obj[property]);// Examplepluck([{ name: 'John', age: 20 },{ name: 'Smith', age: 25 },{ name: 'Peter', age: 30 },],'name'); // ['John', 'Smith', 'Peter']
const getValue = (path, obj) => path.split('.').reduce((acc, c) => acc && acc[c], obj);// ExamplegetValue('a.b', { a: { b: 'Hello World' } }); // 'Hello World';
const renameKeys = (keysMap, obj) =>Object.keys(obj).reduce((acc, key) => ({ ...acc, ...{ [keysMap[key] || key]: obj[key] } }), {});// Examplesconst obj = { a: 1, b: 2, c: 3 };const keysMap = { a: 'd', b: 'e', c: 'f' };renameKeys(keysMap, obj); // { d: 1, e: 2, f: 3 }
const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});// Orconst invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));// Exampleinvert({ a: '1', b: '2', c: '3' }); // { 1: 'a', 2: 'b', 3: 'c' }
const omit = (obj, keys) =>Object.keys(obj).filter((k) => !keys.includes(k)).reduce((res, k) => Object.assign(res, { [k]: obj[k] }), {});// Exampleomit({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { c: '3' }
const pick = (obj, keys) =>Object.keys(obj).filter((k) => keys.includes(k)).reduce((res, k) => Object.assign(res, { [k]: obj[k] }), {});// Examplepick({ a: '1', b: '2', c: '3' }, ['a', 'b']); // { a: '1', b: '2' }
const removeNullUndefined = (obj) => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});// Orconst removeNullUndefined = (obj) =>Object.entries(obj).filter(([_, v]) => v != null).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});// Orconst removeNullUndefined = (obj) => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));// ExampleremoveNullUndefined({foo: null,bar: undefined,fuzz: 42,}); // { fuzz: 42 }
const shallowCopy = obj => Object.assign({}, obj);// orconst shallowCopy = obj => {...obj};
const sort = (obj) =>Object.keys(obj).sort().reduce((p, c) => ((p[c] = obj[c]), p), {});// Exampleconst colors = {white: '#ffffff',black: '#000000',red: '#ff0000',green: '#008000',blue: '#0000ff',};sort(colors);/*{black: '#000000',blue: '#0000ff',green: '#008000',red: '#ff0000',white: '#ffffff',}*/
const randomBoolean = () => Math.random() >= 0.5;
const randomFloat = (min, max) => Math.random() * (max - min) + min;
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;// Orconst randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;
const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const randomIp = () =>Array(4).fill(0).map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0)).join('.');// ExamplerandomIp(); // 175.89.174.131
const randomSign = () => (Math.random() >= 0.5 ? 1 : -1);
const generateString = (length, chars) =>Array(length).fill('').map((v) => chars[Math.floor(Math.random() * chars.length)]).join('');// ExamplegenerateString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
const randomStr = () => require('crypto').randomBytes(32).toString('hex');
const generateString = (length) =>Array(length).fill('').map((v) => Math.random().toString(36).charAt(2)).join('');
const uuid = (a) =>a? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16): ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid);
const randomArrayInRange = (min, max, n) =>Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);// ExamplerandomArrayInRange(1, 100, 10); // [11, 82, 41, 35, 76, 83, 43, 15, 60, 54]
const randomItem = (arr) => arr.splice((Math.random() * arr.length) | 0, 1);// Exampleconst arr = [1, 3, 5, 7, 9];randomItem(arr); // 7// arr = [1, 3, 5, 9]
const randomItem = (arr) => arr[(Math.random() * arr.length) | 0];
const randomItems = (arr, count) =>arr.concat().reduce((p, _, __, arr) =>p[0] < count ? [p[0] + 1, p[1].concat(arr.splice((Math.random() * arr.length) | 0, 1))] : p,[0, []])[1];// ExamplesrandomItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); // [4, 8, 5]randomItems(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 4); // ['e', 'c', 'h', 'j']
const randomProp = (obj) => Object.keys(obj)[(Math.random() * Object.keys(obj).length) | 0];// Exampleconst colors = {aqua: '#00ffff',azure: '#f0ffff',beige: '#f5f5dc',black: '#000000',blue: '#0000ff',brown: '#a52a2a',cyan: '#00ffff',darkblue: '#00008b',darkcyan: '#008b8b',darkgrey: '#a9a9a9',darkgreen: '#006400',darkkhaki: '#bdb76b',darkmagenta: '#8b008b',darkolivegreen: '#556b2f',darkorange: '#ff8c00',darkorchid: '#9932cc',darkred: '#8b0000',darksalmon: '#e9967a',darkviolet: '#9400d3',fuchsia: '#ff00ff',gold: '#ffd700',green: '#008000',indigo: '#4b0082',khaki: '#f0e68c',lightblue: '#add8e6',lightcyan: '#e0ffff',lightgreen: '#90ee90',lightgrey: '#d3d3d3',lightpink: '#ffb6c1',lightyellow: '#ffffe0',lime: '#00ff00',magenta: '#ff00ff',maroon: '#800000',navy: '#000080',olive: '#808000',orange: '#ffa500',pink: '#ffc0cb',purple: '#800080',violet: '#800080',red: '#ff0000',silver: '#c0c0c0',white: '#ffffff',yellow: '#ffff00',};randomProp(colors); // 'red'
const randomLines = (str, count) =>str.split(/\r?\n/).reduce((p, _, __, arr) =>p[0] < count ? [p[0] + 1, p[1].concat(arr.splice((Math.random() * arr.length) | 0, 1))] : p,[0, []])[1];// ExamplerandomLines(`onetwothreefourfive`,2);// ['one', 'four']
const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;// Orconst capitalize = ([first, ...rest]) => `${first.toUpperCase()}${rest.join('')}`;// Examplecapitalize('hello world'); // 'Hello world'
const isRelative = (path) => !/^([a-z]+:)?[\\/]/i.test(path);// ExamplesisRelative('/foo/bar/baz'); // falseisRelative('C:\\foo\\bar\\baz'); // falseisRelative('foo/bar/baz.txt'); // trueisRelative('foo.md'); // true
const consistsRepeatedSubstring = (str) => `${str}${str}`.indexOf(str, 1) !== str.length;// ExampleconsistsRepeatedSubstring('aa'); // trueconsistsRepeatedSubstring('aaa'); // trueconsistsRepeatedSubstring('ababab'); // trueconsistsRepeatedSubstring('abc'); // false
const isPalindrome = (str) => str === str.split('').reverse().join('');// ExamplesisPalindrome('abc'); // falseisPalindrom('abcba'); // true
const isAbsoluteUrl = (url) => /^[a-z][a-z0-9+.-]*:/.test(url);// ExampleisAbsoluteUrl('https://1loc.dev'); // trueisAbsoluteUrl('https://1loc.dev/foo/bar'); // trueisAbsoluteUrl('1loc.dev'); // falseisAbsoluteUrl('//1loc.dev'); // false
const areAnagram = (str1, str2) =>str1.toLowerCase().split('').sort().join('') === str2.toLowerCase().split('').sort().join('');// ExamplesareAnagram('listen', 'silent'); // trueareAnagram('they see', 'the eyes'); // trueareAnagram('node', 'deno'); // true
const letterToEmoji = (c) => String.fromCodePoint(c.toLowerCase().charCodeAt() + 127365);// ExamplesletterToEmoji('a'); // 🇦letterToEmoji('b'); // 🇧
const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));// ExamplestoCamelCase('background-color'); // backgroundColortoCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumbtoCamelCase('_hello_world'); // HelloWorldtoCamelCase('hello_world'); // helloWorld
const toPascalCase = (str) =>(str.match(/[a-zA-Z0-9]+/g) || []).map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join('');// ExamplestoPascalCase('hello world'); // 'HelloWorld'toPascalCase('hello.world'); // 'HelloWorld'toPascalCase('foo_bar-baz'); // FooBarBaz
const slugify = (string) =>string.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');// Exampleslugify('Chapter One: Once upon a time...'); // 'chapter-one-once-upon-a-time'
const toUnixPath = (path) => path.replace(/[\\/]+/g, '/').replace(/^([a-zA-Z]+:|\.\/)/, '');// ExamplestoUnixPath('./foo/bar/baz'); // foo/bar/baztoUnixPath('C:\\foo\\bar\\baz'); // /foo/bar/baz
const kebabToCamel = (str) => str.replace(/-./g, (m) => m.toUpperCase()[1]);const camelToKebab = (str) => str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();// ExampleskebabToCamel('background-color'); // 'backgroundColor'camelToKebab('backgroundColor'); // 'background-color'
const snakeToCamel = (str) => str.toLowerCase().replace(/(_\w)/g, (m) => m.toUpperCase().substr(1));// ExamplesnakeToCamel('HELLO_world'); // 'helloWorld'
const getIndex = (col) => col.split('').reduce((prev, next) => prev * 26 + parseInt(next, 36) - 9, 0);// ExamplesgetIndex('A'); // 1getIndex('B'); // 2getIndex('C'); // 3getIndex('Z'); // 26getIndex('AA'); // 27getIndex('AB'); // 28getIndex('AC'); // 29getIndex('AZ'); // 52getIndex('AAA'); // 703getIndex('AAB'); // 704
const countWords = (str) => str.trim().split(/\s+/).length;// ExamplecountWords('Hello World'); // 2countWords('Hello World'); // 2countWords(' Hello World '); // 2
const countOccurrences = (str, char) => [...str].reduce((a, v) => (v === char ? a + 1 : a), 0);// Orconst countOccurrences = (str, char) => str.split('').reduce((a, v) => (v === char ? a + 1 : a), 0);// Orconst countOccurrences = (str, char) => [...str].filter((item) => item === char).length;// Orconst countOccurrences = (str, char) => str.split('').filter((item) => item === char).length;// ExamplescountOccurrences('a.b.c.d.e', '.'); // 4
const decapitalize = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;// Orconst decapitalize = ([first, ...rest]) => `${first.toLowerCase()}${rest.join('')}`;// Exampledecapitalize('Hello world'); // 'hello world'
const escape = (str) =>str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/"/g, '"');// Orconst escape = (str) =>str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]));
const hash = (str) => str.split('').reduce((prev, curr) => (Math.imul(31, prev) + curr.charCodeAt(0)) | 0, 0);// Orconst hash = (str) => str.split('').reduce((prev, curr) => ((prev << 5) - prev + curr.charCodeAt(0)) | 0, 0);// Examplehash('hello'); // 99162322
const baseUrl = (url) => (url.indexOf('?') === -1 ? url : url.slice(0, url.indexOf('?')));// Or// Note that `includes` isn't supported in IE 11const baseUrl = (url) => (url.includes('?') ? url.slice(0, url.indexOf('?')) : url);// Orconst baseUrl = (url) => url.split('?')[0];// ExamplebaseUrl('https://domain.com/path/sub/path?foo=bar&hello=world'); // 'https://domain.com/path/sub/path'
const ext = (fileName) => fileName.split('.').pop();
const fileName = (url) => url.substring(url.lastIndexOf('/') + 1);// ExamplefileName('http://domain.com/path/to/document.pdf'); // 'document.pdf'
const bytes = (str) => new Blob([str]).size;// Examplesbytes('hello world'); // 11bytes('🎉'); // 4
const characterCount = (str, char) => str.split(char).length - 1;// Orconst characterCount = (str, char) => str.replace(new RegExp(String.raw`[^${char}]`, 'g'), '').length;// ExamplescharacterCount('192.168.1.1', '.'); // 3characterCount('star wars', 's'); // 2
const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;// ExamplelowercaseFirst('Hello World'); // 'hello World'
const normalizePath = (path) => path.replace(/[\\/]+/g, '/');// ExamplenormalizePath('\\foo\\bar\\baz\\'); // /foo/bar/baz/normalizePath('.//foo//bar///////baz/'); // ./foo/bar/baz/
const prependNumbers = (str) =>str.split(/\r?\n/).map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`).join('\n');// ExampleprependNumbers(`onetwothreefour`);/* Output *//*1 one2 two3 three4 four*/
const removeDuplicateLines = (str) => Array.from(new Set(str.split(/\r?\n/))).join('\n');// ExampleremoveDuplicateLines(`onethreetwothreeonefour`);/* Output *//*onethreetwofour*/
const removeEmptyLines = (str) =>str.split(/\r?\n/).filter((line) => line.trim() !== '').join('\n');// ExampleremoveEmptyLines(`redgreenblueyellow`);/* Output *//*redgreenblueyellow*/
const removeSpaces = (str) => str.replace(/\s/g, '');// ExampleremoveSpaces('hel lo wor ld'); // 'helloworld'
const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes);// Orconst repeat = (str, numberOfTimes) => Array(numberOfTimes + 1).join(str);
const nl2br = (str) => str.replace(new RegExp('\r?\n', 'g'), '<br>');// In Reactstr.split('\n').map((item, index) => (<React.Fragment key={index}>{item}<br /></React.Fragment>));
const replace = (str, numSpaces = 4) => str.replaceAll('\t', ' '.repeat(numSpaces));
// Replace spaces, tabs and new line charactersconst replaceSpaces = (str) => str.replace(/\s\s+/g, ' ');// Only replace spacesconst replaceOnlySpaces = (str) => str.replace(/ +/g, ' ');// ExamplereplaceSpaces('this\n is \ta \rmessage'); // 'this is a message'
const mask = (str, num, mask) => `${str}`.slice(num).padStart(`${str}`.length, mask);// Examplemask(1234567890, 3, '*'); // ***4567890
const reverse = (str) => str.split('').reverse().join('');// Orconst reverse = (str) => [...str].reverse().join('');// Orconst reverse = (str) => str.split('').reduce((rev, char) => `${char}${rev}`, '');// Orconst reverse = (str) => (str === '' ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`);// Examplereverse('hello world'); // 'dlrow olleh'
const reverseLines = (str) => str.split(/\r?\n/).reverse().join('\n');// ExamplereverseLines(`onetwothree`);/* Output *//*threetwoone*/
const sortLines = (str) => str.split(/\r?\n/).sort().join('\n');// Reverse the orderconst reverseSortedLines = (str) => str.split(/\r?\n/).sort().reverse().join('\n');// ExamplesortLines(`Thaddeus MullenKareem MarshallFerdinand ValentineHasad LindsayMufutau BergKnox TysonKasimir FletcherColton SharpAdrian RosalesTheodore Rogers`);/* Output *//*Adrian RosalesColton SharpFerdinand ValentineHasad LindsayKareem MarshallKasimir FletcherKnox TysonMufutau BergThaddeus MullenTheodore Rogers*/
const sort = (str) =>str.split('').sort((a, b) => a.localeCompare(b)).join('');// Examplesort('hello world'); // dehllloorw
const stripAnsiCodes = (str) =>str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');// ExamplestripAnsiCodes('\u001B[4mcake\u001B[0m'); // 'cake'stripAnsiCodes('\u001B[0m\u001B[4m\u001B[42m\u001B[31mfoo\u001B[39m\u001B[49m\u001B[24mfoo\u001B[0m'); // 'foofoo'
const swapCase = (str) =>str.split('').map((c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase())).join('');// ExampleswapCase('Hello World'); // 'hELLO wORLD'
const trimSlashes = (str) => str.replace(/^\/+|\/+$/g, '');// Orconst trimSlashes = (str) => str.split('/').filter(Boolean).join('/');// ExampletrimSlashes('//hello/world///'); // hello/world
const trim = (str, char) => str.split(char).filter(Boolean).join();// Examplestrim('/hello world//', '/'); // hello worldtrim('"hello world"', '"'); // hello worldtrim(' hello world ', ' '); // hello world
const trimExt = (fileName) => (fileName.indexOf('.') === -1 ? fileName : fileName.split('.').slice(0, -1).join('.'));// ExamplestrimExt('document'); // documenttrimExt('document.pdf'); // documenttrimExt('document.2020.pdf'); // document.2020
const truncate = (str, max, suffix) =>str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`;// Exampletruncate('This is a long message', 20, '...'); // 'This is a long...'
const unescape = (str) =>str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/�*39;/g, "'").replace(/"/g, '"');
const uppercaseWords = (str) =>str.split(' ').map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join(' ');// Orconst uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase());// ExampleuppercaseWords('hello world'); // 'Hello World'
// `date` is a Date objectconst isWeekday = (date = new Date()) => date.getDay() % 6 !== 0;
// `date` is a Date objectconst isWeekend = (date = new Date()) => date.getDay() % 6 === 0;
// `min`, `max` and `date` are `Date` instancesconst isBetween = (date, min, max) => date.getTime() >= min.getTime() && date.getTime() <= max.getTime();
// `date` is a Date objectconst isToday = (date) => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10);
// `date` is a Date objectconst isCurrentYear = (date) => date.getUTCFullYear() === new Date().getUTCFullYear();
const hasDuplicateValues = (arr) => new Set(arr).size !== arr.length;// ExampleshasDuplicateValues(['h', 'e', 'l', 'l', 'o']); // truehasDuplicateValues(['w', 'o', 'r', 'd']); // false
const isPrime = (num) =>num > 1 &&Array(Math.floor(Math.sqrt(num)) - 1).fill(0).map((_, i) => i + 2).every((i) => num % i !== 0);
const isPowerOfTwo = (number) => (number & (number - 1)) === 0;// ExamplesisPowerOfTwo(256); // trueisPowerOfTwo(129); // false
const isEven = (number) => number % 2 === 0;// Orconst isEven = (number) => (number & 1) === 0;// Orconst isEven = (number) => !(number & 1);// Orconst isEven = (number) => Number.isInteger(number / 2);// ExamplesisEven(1); // falseisEven(2); // true
const inRange = (num, a, b, threshold = 0) => Math.min(a, b) - threshold <= num && num <= Math.max(a, b) + threshold;// ExampleinRange(10, 5, 15); // trueinRange(10, 5, 6); // falseinRange(10, 15, 5); // trueinRange(-10, -5, -15); // true
const isNegative = (number) => Math.sign(number) === -1;// Orconst isNegative = (number) => number < 0;// ExamplesisNegative(-3); // trueisNegative(8); // false
const isOdd = (number) => number % 2 !== 0;// Orconst isOdd = (number) => !!(number & 1);// Orconst isOdd = (number) => !Number.isInteger(number / 2);// ExamplesisOdd(1); // trueisOdd(2); // false
const isPositive = (number) => Math.sign(number) === 1;// ExamplesisPositive(3); // trueisPositive(-8); // false
const containsLowerCase = (str) => str !== str.toUpperCase();// ExamplescontainsLowerCase('Hello World'); // truecontainsLowerCase('HELLO WORLD'); // false
const isAscii = (str) => /^[\x00-\x7F]+$/.test(str);
const isNumeric = (str) => !/[^0-9]/.test(str);// ExamplesisNumeric(2); // trueisNumeric('23'); // trueisNumeric('00123'); // trueisNumeric('1.23'); // falseisNumeric('-Infinity'); // falseisNumeric('Infinity'); // falseisNumeric('NaN'); // false
const isAlphanumeric = (str) => /^[0-9A-Z]+$/i.test(str);// ExamplesisAlphanumeric('helloworld'); // trueisAlphanumeric('HelloWorld'); // trueisAlphanumeric('hello world'); // falseisAlphanumeric('hello123'); // trueisAlphanumeric('hello 123'); // false
const isAlpha = (str) => /^[A-Z]+$/i.test(str);// ExamplesisAlpha('helloworld'); // trueisAlpha('HelloWorld'); // trueisAlpha('hello world'); // falseisAlpha('0123456789'); // false
const containsUpperCase = (str) => str !== str.toLowerCase();// ExamplescontainsUpperCase('Hello World'); // truecontainsUpperCase('hello world'); // false
const containsWhitespace = (str) => (str) => /\s/.test(str);// ExamplecontainsWhitespace('hello world'); // true
const isHexColor = (color) => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color);// ExamplesisHexColor('#012'); // trueisHexColor('#A1B2C3'); // trueisHexColor('012'); // falseisHexColor('#GHIJKL'); // false
const isHexadecimal = (str) => /^[A-F0-9]+$/i.test(str);// Orconst isHexadecimal = (str) => str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);// ExamplesisHexadecimal('123'); // trueisHexadecimal('A1B2C3'); // trueisHexadecimal('#123'); // false
const isMongoId = (str) => str.length === 24 && /^[A-F0-9]+$/i.test(str);// Orconst isMongoId = (str) => str.length === 24 && str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);
const isOctal = (str) => /^(0o)?[0-7]+$/i.test(str);
const isLowerCase = (str) => str === str.toLowerCase();
const isUpperCase = (str) => str === str.toUpperCase();
const isBIC = (value) => /^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(value);
const isNumber = (value) => !isNaN(parseFloat(value)) && isFinite(value);
const isPlainObject = (v) => !!v && typeof v === 'object' && (v.__proto__ === null || v.__proto__ === Object.prototype);// ExamplesisPlainObject(null); // falseisPlainObject('hello world'); // falseisPlainObject([]); // falseisPlainObject(Object.create(null)); // falseisPlainObject(function () {}); // falseisPlainObject({}); // trueisPlainObject({ a: '1', b: '2' }); // true
const isRegExp = (value) => Object.prototype.toString.call(value) === '[object RegExp]';
const isString = (value) => Object.prototype.toString.call(value) === '[object String]';// ExamplesisString('hello world'); // trueisString(new String('hello world')); // trueisString(10); // false
const isObject = (v) => v !== null && typeof v === 'object';// ExamplesisObject(null); // falseisObject('hello world'); // falseisObject({}); // trueisObject([]); // true
const isBase32 = (value) => value.length % 8 === 0 && /^[A-Z2-7]+=*$/.test(value);
// It doesn't accept the I, O, l charactersconst isBase58 = (value) => /^[A-HJ-NP-Za-km-z1-9]*$/.test(value);
const isBase64 = (value) =>/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value);
const isNil = (value) => value == null;
const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;// Or// Get the number of days in Februaryconst isLeapYear = (year) => new Date(year, 1, 29).getDate() === 29;
const isEqual = (arr, value) => arr.every((item) => item === value);// Or// Ends earlier for false arraysconst isEqual = (arr, value) => !arr.some((item) => item !== value);// ExamplesisEqual(['foo', 'foo'], 'foo'); // trueisEqual(['foo', 'bar'], 'foo'); // falseisEqual(['bar', 'bar'], 'foo'); // false
const areEqual = (arr) => arr.length > 0 && arr.every((item) => item === arr[0]);// Orconst areEqual = (arr) => new Set(arr).size === 1;// ExamplesareEqual([1, 2, 3, 4]); // falseareEqual(['hello', 'hello', 'hello']); // true
const contains = (arr, criteria) => arr.some((v) => criteria(v));// Orconst contains = (arr, criteria) => arr.some(criteria);// Orconst contains = (arr, criteria) => arr.filter(criteria).length > 0;// Examplescontains([10, 20, 30], (v) => v > 25); // truecontains([10, 20, 30], (v) => v > 100 || v < 15); // truecontains([10, 20, 30], (v) => v > 100); // false
const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;// ExamplesisNotEmpty([]); // falseisNotEmpty([1, 2, 3]); // true
// Check if `b` is subset of `a`const isSubset = (a, b) => new Set(b).size === new Set(b.concat(a)).size;// Orconst isSubset = (a, b) => b.join('|').includes(a.join('|'));// ExamplesisSubset([1, 2], [1, 2, 3, 4]); // trueisSubset([1, 2, 5], [1, 2, 3, 4]); // falseisSubset([6], [1, 2, 3, 4]); // false
const isPromise = (obj) =>!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
const isArray = (obj) => Array.isArray(obj);
const isEmpty = (obj) => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;// Or for enumerable property names onlyconst isEmpty = (obj) => JSON.stringify(obj) === '{}';
// `m`: the month (zero-based index)// `d`: the day// `y`: the yearconst isValidDate = (m, d, y) => 0 <= m && m <= 11 && 0 < y && y < 32768 && 0 < d && d <= new Date(y, m, 0).getDate();