• Author: Chen Da Yu Tou
  • Making: KRISACHAN

In order to cut down on overtime and spend more time with my girlfriend, I shamelessly asked some BAT bosses for these 15 JS tips, and now I share them with you. Don’t miss them.

The body of the

Returns the date subscript closest to the target sequence in the date sequence

const getNearestDateIndex = (targetDate, dates) = > {
    if(! targetDate || ! dates) {throw new Error('Argument(s) is illegal ! ')}if(! dates.length) {return -1
    }
    const distances = dates.map(date= > Math.abs(date - targetDate))
    return distances.indexOf(Math.min(... distances)) }// e.g.
const targetDate = new Date(2019.7.20)
const dates = [
  new Date(2018.0.1),
  new Date(2019.0.1),
  new Date(2020.0.1),
]
getNearestDateIndex(targetDate, dates) / / 2
Copy the code

Returns the smallest date in the date column

const getMinDate = dates= > {
    if(! dates) {throw new Error('Argument(s) is illegal ! ')}if(! dates.length) {return dates
	}
    return new Date(Math.min.apply(null, dates)).toISOString()
}

// e.g.
const dates = [
  new Date(2018.3.10),
  new Date(2019.3.10),
  new Date(2020.3.10),
]
getMinDate(dates) / / T16 2018-04-09:00:00. 000 z
Copy the code

Disrupted array

const arrayShuffle = array= > {
    if (!Array.isArray(array)) {
        throw new Error('Argument must be an array')}let end = array.length
    if(! end) {return array
    }
    while (end) {
        let start = Math.floor(Math.random() * end--) ; [array[start], array[end]] = [array[end], array[start]] }return array
}

// e.g.
arrayShuffle([1.2.3])
Copy the code

Determine whether the WebP image format is supported

const canUseWebp = () = > (document.createElement('canvas').toDataURL('image/webp'.0.5).indexOf('data:image/webp') = = =0)

// e.g.
canUseWebp() // True in new Chrome, false in Firefox
Copy the code

Check whether it is a URL

const isUrl = str= > /^(((ht|f)tps?) : \ \ /)? [\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])? $/.test(str)

// e.g.
isUrl('https://www.baidu.com') // true
isUrl('https://www') // false
Copy the code

Determine if it’s emoji

const isEmoji = str= > /(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f\ude80-\udeff])|[\u2600-\u2B55]/g.test(str)

// e.g.
isEmoji('🌏') // true
isEmoji('earth') // false
Copy the code

Hyphen to hump

const toCamelCase = (str = ' ', separator = The '-') = > {
    if (typeofstr ! = ='string') {
        throw new Error('Argument must be a string')}if (str === ' ') {
        return str
    }
    const newExp = new RegExp('\\-\(\\w\)'.'g')
    return str.replace(newExp, (matched, $1) = > {
        return $1.toUpperCase()
    })
}

// e.g.
toCamelCase('hello-world') // helloWorld
Copy the code

Hump to hyphen

const fromCamelCase = (str = ' ', separator = The '-') = > {
    if (typeofstr ! = ='string') {
        throw new Error('Argument must be a string')}if (str === ' ') {
        return str
    }
    return str.replace(/([A-Z])/g.`${separator}$1 `).toLowerCase()
}

// e.g.
fromCamelCase('helloWorld') // hello-world
Copy the code

Level to judge

const getLevel = (value = 0, ratio = 50, levels = One, two, three, four, five.) = > {
    if (typeofvalue ! = ='number') {
        throw new Error('Argument must be a number')}const levelHash = One, two, three, four, five..split(' ')
	const max = levelHash[levelHash.length - 1]
	return levelHash[Math.floor(value / ratio)] || max
}

// e.g.
getLevel1(0) / / a
getLevel1(40) / / a
getLevel(77) / / 2
Copy the code

Event simulation trigger

const event = new Event('click')
const body = document.querySelector('body')
body.addEventListener('click'.ev= > {
    console.log('biu')},false)
body.addEventListener('touchmove'.ev= > {
    body.dispatchEvent(event)
}, false)
// The click event is triggered when you slide your finger down on the mobile
Copy the code

Determine if the DOM is equal

const isEqualNode = (dom1, dom2) = > dom1.isEqualNode(dom2)

/* 
      
this is the first div
this is the second div
this is the first div */
const[one, two, three,] =document.getElementsByTagName('div') // e.g.IsEqualNode (one, two)// falseIsEqualNode (1, 3)// trueIsEqualNode (two, three)// false Copy the code

Multi-attribute bidirectional binding

/* 
      
*/
const keys = Object .values(box.attributes) .map(({name, value}) = > ({name, value})) const cacheData = {} const properties = keys.reduce((acc, cur) = > { const obj = {} cacheData[cur.name] = box.attributes[cur.name] obj[cur.name] = { get() { return cacheData[cur.name] }, set(data) { output.value = `${cur.name}: ${data}` cacheData[cur.name] = data } } return{... acc, ... obj } }, {})Object.defineProperties(box, properties) // When we modify the corresponding attribute of the input, the output text becomes the modified content Copy the code

Gets a random number in a specified range

const getRandom = (min = 0, max = 100) = > {
    if (typeofmin ! = ='number' || typeofmax ! = ='number') {
        throw new Error('Argument(s) is illegal ! ')}if (min > max) {
        [min, max] = [max, min]
    }
    return Math.floor(Math.random() * (max - min + 1) + min)
}

// e.g.
getRandom(1.100) / / 89
getRandom(1.100) / / 5
Copy the code

File size formatting

const formatSize = size= > {
    if (typeof+size ! = ='number') {
        throw new Error('Argument(s) is illegal ! ')}const unitsHash = 'B,KB,MB,GB'.split(', ')
    let index = 0
    while (size > 1024 && index < unitsHash.length) {
        size /= 1024
        index++
    }
    return Math.round(size * 100) / 100 + unitsHash[index]
}
formatSize('10240') // 10KB
formatSize('10240000') / / 9.77 MB
Copy the code

Gets a specified number of elements before and after an array

const arrayRange = (array, index, distance = '+') = > {
    if (!Array.isArray(array) || typeofindex ! = ='number' || index < 0) {
        throw new TypeError('Argument(s) is illegal');
    }
    return array.slice(0.`${distance}${index}`)
}

arrayRange(['a'.'b'.'c'].2) // ["a", "b"]
arrayRange(['a'.'b'.'c'].2.The '-') // ["a"]
Copy the code

Afterword.

The above 15 JS skills are fish head hard from a few big factory bosses kneel out, I hope you can make good use of in the business, reduce the number of overtime.

If you like to discuss technology, or have any comments or suggestions on this article, you are welcome to add yu Tou wechat friends to discuss. Of course, Yu Tou also hopes to talk about life, hobbies and things with you. His wechat id is krisChans95