Array
generate array
when you need to generate an array of 0-99
scenario 1
const createArr = (n) => Array.from(new Array(n), (v, i) => i)
const arr = createArr(100) // 0-99 array
scenario 2
const createArr = (n) => new Array(n).fill(0).map((v, i) => i)
createArr(100) // 0-99 array
disrupt the array
when you have an array, you need to disrupt the sorting of the array
const randomSort = list => list.sort(() => Math.random() - 0.5)
randomSort([0,1,2,3,4,5,6,7,8,9]) // randomly arrange the results
Array deduplication
when you need to keep only one
for all the repeating elements in the array
const removeDuplicates = list => [...new Set(list)]
removeDuplicates([0, 0, 2, 4, 5]) // [0,2,4,5]
most groups take intersection
when you need to take the intersection of multiple arrays
const intersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)))
intersection([1, 2, 3, 4], [2, 3, 4, 7, 8], [1, 3, 4, 9])
// [3, 4]
find maximum index
but you need to find an index of the largest value in the array
const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);
indexOfMax([1, 3, 9, 7, 5]); // 2
find the minimum index
when you need to find the index of the lowest value in an array
const indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0)
indexOfMin([2, 5, 3, 4, 1, 0, 9]) // 5
find the nearest value
when you need to find the closest value in an array
const closest = (arr, n) => arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev))
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50) // 33
compress multiple arrays
when you need to compress multiple arrays into one
const zip = (...arr) => Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_, i) => arr.map((a) => a[i]))
zip([1,2,3,4], ['a', 'b', 'c', 'd'], ['A', 'B', 'C', 'D'])
// [[1, 'a', 'A'], [2, 'b', 'B'], [3, 'c', 'C'], [4, 'd', 'D']]
Matrix swap rows and columns
when you need to exchange rows and columns of a matrix with each other
const transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i]));
transpose(
[ // [
[1, 2, 3], // [1, 4, 7],
[4, 5, 6], // [2, 5, 8],
[7, 8, 9], // [3, 6, 9],
] // ]
);
Digital conversion
binary conversion
convert decimal to n, you can use toString (n)
const toDecimal = (num, n = 10) => num.toString(n)
// suppose the number 10 is to be converted to binary
toDecimal(10, 2) // '1010'
convert n-ary to 10-ary, you can use parseInt (num, n)
The binary of // 10 is 1010.
const toDecimalism = (num, n = 10) => parseInt(num, n)
toDecimalism(1010, 2)
regular
Mobile number formatting
when you need to format your mobile phone number into xxx-xxxx-xxxx
const formatPhone = (str, sign = '-') => str.replace(/(\W|\s)/g, "").split(/^(\d{3})(\d{4})(\d{4})$/).filter(item => item).join(sign)
formatPhone('13123456789') // '131-2345-6789'
formatPhone('13 1234 56 789', ' ') // '131 2345 6789'
remove extra spaces
when you need to merge multiple spaces in a paragraph of text into one space
const setTrimOut = str => str.replace(/\s\s+/g, ' ')
const str = setTrimOut('hello, jack') //
web
reload the current page
const reload = () => location.reload();
reload()
scroll to the top of the page
if you need to turn the page to the top
const goToTop = () => window.scrollTo(0, 0);
goToTop()
element scrolling
if you want to scroll an element smoothly to the starting point of the visual area
const scrollToTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" })
scrollToTop(document.body)
if you want to scroll an element smoothly to the end of the visual area
const scrollToBottom = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "end" })
scrollToBottom(document.body)
check whether the IE browser is currently available
const isIE = !!document.documentMode;
stripping html from a given text
when you need to filter out all the tags in a text
const stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || '';
stripHtml('<div>test</div>') // 'test'
redirect
when you need to jump to another page
const goTo = (url) => (location.href = url);
text paste
when you need to copy text to the pasteboard
const copy = (text) => navigator.clipboard?.writeText && navigator.clipboard.writeText(text)
copy('The text you need to paste')
date
determine whether the date is today
const isToday = (date) => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10)
date conversion
when you need to convert the date to YYYY-MM-DD format
const formatYmd = (date) => date.toISOString().slice(0, 10);
formatYmd(new Date())
second conversion
when you need to convert seconds to hh:mm:ss format
const formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8)
formatSeconds(200) // 00:03:20
get the first day of a certain month in a year
when you need to get the first day of a certain month of a year
const getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1);
getFirstDate(new Date('2022-04')) // Fri Apr 01 2022 00:00:00 GMT+0800 (China Standard time)
get the last day of a certain month in a year
when you need to get the last day of a certain month of a year
const getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() + 1, 0);
getLastDate(new Date('2023-03-04')) // Fri Mar 31 2023 00:00:00 GMT+0800 (China Standard time)
get the number of days in a year
when you need to get the total number of days in a certain month of a year
const getDaysNum = (year, month) => new Date(year, month, 0).getDate()
const day = getDaysNum(2024, 2) // 29
function
Asynchronous function judgment
determine whether a function belongs to an asynchronous function
const isAsyncFunction = (v) => Object.prototype.toString.call(v) === '[object AsyncFunction]'
isAsyncFunction(async function () {}); // true
numbers
truncation number
when you need to truncate some numbers after the decimal point instead of rounding
const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\d+(?:.\d{0,${fixed}})?`))[0]
toFixed(10.255, 2) // 10.25
rounding
when you need to truncate some numbers after the decimal point and round them
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
round(10.255, 2) // 10.26
zero padding
when you need to fill in zeros before a number num is less than len digits
const replenishZero = (num, len, zero = 0) => num.toString().padStart(len, zero)
replenishZero(8, 2) // 08
object
Delete invalid attributes
when you need to delete all properties in an object whose value is null or undefined
const removeNullUndefined = (obj) => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});
removeNullUndefined({name: '', age: undefined, sex: null}) // { name: '' }
reverse object key
when you need to swap the key-value pairs of an object
const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {})
invert({name: 'jack'}) // {jack: 'name'}
string transfer object
when you need to convert a string of strings such as'{name: "jack"}'to an object, using JSON.parse directly will cause an error.
const strParse = (str) => JSON.parse(str.replace(/(\w+)\s*:/g, (_, p1) => `"${p1}":`).replace(/\'/g, "\""))
strParse('{name: "jack"}')
other
compare two objects
when you need to compare two objects, the js can only determine whether the address of the object is the same. When the address is different, it is impossible to determine whether the key-value pairs of the two objects are the same.
const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]))
isEqual({name: 'jack'}, {name: 'jack'}) // true
isEqual({name: 'jack'}, {name: 'jack1'}, {name: 'jack'}) // false
Random color generation
when you need to get a random color
const getRandomColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`
getRandomColor() // '#4c2fd7'
Color format conversion
when you need to convert hexadecimal colors 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));
hexToRgb('#00ffff'); // [0, 255, 255]
hexToRgb('#0ff'); // [0, 255, 255]
get random ip
when you need to generate an ip address
const randomIp = () =>
Array(4)
.fill(0)
.map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0))
.join('.');
uuid
when you need to generate an id
const uuid = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid))
uuid()
get cookie
when you need to convert cookie to an object
const getCookie = () => document.cookie
.split(';')
.map((item) => item.split('='))
.reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {})
getCookie()
forced waiting
when you need to wait for a period of time, but do not want to write in the setTimeout function, resulting in callback hell
const sleep = async (t) => new Promise((resolve) => setTimeout(resolve, t));
sleep(2000).then(() => {console.log('time')});