Generating arrays

 When you need to generate a 0-99 array

const createArr = (n) => Array.from(new Array(n), (v, i) => i)
const arr = createArr(100) // 0 - 99

const createArr = (n) => new Array(n).fill(0).map((v, i) => i)
createArr(100) // 0 - 99

 disrupt an array

 When you have an array, you need to disrupt the ordering of that array

const randomSort = list => list.sort(() => Math.random() - 0.5)
randomSort([0,1,2,3,4,5,6,7,8,9])

 Simple data de-duplication of arrays

 When you need to keep all duplicate elements in an array to just one

const removeDuplicates = list => [...new Set(list)]
removeDuplicates([0, 0, 2, 4, 5]) // [0,2,4,5]

 Array unique value data de-duplication

 De-duplication of arrays based on unique values

const duplicateById = list => [...list.reduce((prev, cur) => prev.set(cur.id, cur), new Map()).values()]
duplicateById([{id: 1, name: 'jack'}, {id: 2, name: 'rose'}, {id: 1, name: 'jack'}])
// [{id: 1, name: 'jack'}, {id: 2, name: 'rose'}]

 Taking the intersection of multiple arrays

 When you need to take the intersection of multiple arrays of

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 the index of the largest value in an array

const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);
indexOfMax([1, 3, 9, 7, 5]); // 2

 Find Minimum Index

 When you need to find the index of the smallest 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 closest value

 When you need to find the closest value in an array of

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

 Compressing multiple arrays

 When you need to compress multiple arrays into a single array

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 swap the 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

 decimal conversion


To convert from decimal to n, you can use toString(n)

const toDecimal = (num, n = 10) => num.toString(n) 

toDecimal(10, 2) // '1010'


To convert n to decimal, you can use parseInt(num, n)


const toDecimalism = (num, n = 10) => parseInt(num, n)
toDecimalism(1010, 2)

 Cell Phone Number Formatting


When you need to format a cell phone number as 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 combine multiple spaces in a paragraph of text into a single 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 top of 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 start 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 if you are currently using Internet Explorer

const isIE = !!document.documentMode;

 Strip html from a given text

 When you need to filter out all the tags in a certain text

const stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || '';
stripHtml('<div>test</div>') // 'test'

 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('...')

 Determine if 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 a date to YYYY-MM-DD format

const formatYmd = (date) => date.toISOString().slice(0, 10);
formatYmd(new Date())

 seconds conversion

 When you need to convert seconds to the 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 the year and month

 When you need to get the first day of a certain year and month

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 

 Get the last day of the month of the year

 When you need to get the last day of a certain month of a certain 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

 Get the number of days in a month in a year

 When you need to get the total number of days in a particular month of a year

const getDaysNum = (year, month) => new Date(year, month, 0).getDate()  
const day = getDaysNum(2024, 2) // 29

 Asynchronous function judgment

 Determining whether a function is asynchronous

const isAsyncFunction = (v) => Object.prototype.toString.call(v) === '[object AsyncFunction]'
isAsyncFunction(async function () {}); // true

 truncated figure

 When you need to truncate certain numbers after the decimal point without rounding them off

const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\d+(?:.\d{0,${fixed}})?`))[0]
toFixed(10.255, 2) // 10.25

 discard four, but treat five as whole (of decimal points)

 When you need to truncate certain numbers after the decimal point and round them up

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
round(10.255, 2) // 10.26


When you need to make up zeros in front of a number with less than len digits in the number num

const replenishZero = (num, len, zero = 0) => num.toString().padStart(len, zero)
replenishZero(8, 2) // 08

 Remove Invalid Attributes


When you need to delete all the properties in an object whose property values are 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: '' }

 Reversing Object Keys

 When you need to swap the key-value pairs of an object’s

const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {})
invert({name: 'jack'}) // {jack: 'name'}

 string to object (computing)


When you need to convert a string such as ‘{name: “jack”}’ into an object, using JSON.parse directly will report an error.

const strParse = (str) => JSON.parse(str.replace(/(\w+)\s*:/g, (_, p1) => `"${p1}":`).replace(/\'/g, "\""))

strParse('{name: "jack"}')

 Comparing two objects


When you need to compare two objects, js’s equals can only determine whether the addresses of the objects are the same, and when the addresses are not the same you can’t 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 a hex color 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()

 Getting cookies

 When you need to convert a cookie into an object

const getCookie = () => document.cookie
    .split(';')
    .map((item) => item.split('='))
    .reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {})
getCookie()

 compulsory waiting


When you need to wait a while, but don’t want to write in the setTimeout function and cause callback hell

const sleep = async (t) => new Promise((resolve) => setTimeout(resolve, t));
sleep(2000).then(() => {console.log('time')});

By lzz

Leave a Reply

Your email address will not be published. Required fields are marked *