Skip to content

Instantly share code, notes, and snippets.

@K-Kevin
Last active August 19, 2020 06:08
Show Gist options
  • Save K-Kevin/d2008c4d70ee9fbbeb123f6227483db9 to your computer and use it in GitHub Desktop.
Save K-Kevin/d2008c4d70ee9fbbeb123f6227483db9 to your computer and use it in GitHub Desktop.
JS 技巧
返回日期数列里与目标数列最近的日期下标
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
返回日期数列里最小的日期
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) // 2018-04-09T16:00:00.000Z
打乱数组
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])
判断是否支持webp图片格式
const canUseWebp = () => (document.createElement('canvas').toDataURL('image/webp', 0.5).indexOf('data:image/webp') === 0)

// e.g.
canUseWebp() // 新版的chrome里为true,火狐里为false
判断是否是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
判断是否是emoji
const isEmoji = str => /(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f\ude80-\udeff])|[\u2600-\u2B55]/g.test(str)

// e.g.
isEmoji('🌏') // true
isEmoji('earth') // false
连字符转驼峰
const toCamelCase = (str = '', separator = '-') => {
    if (typeof str !== '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
驼峰转连字符
const fromCamelCase = (str = '', separator = '-') => {
    if (typeof str !== '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
事件模拟触发
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)
// 这时候在移动端下滑动手指的时候就会触发click事件
判断dom是否相等
const isEqualNode = (dom1, dom2) => dom1.isEqualNode(dom2)

/*
    <div>这是第一个div</div>
    <div>这是第二个div</div>
    <div>这是第一个div</div>
*/
const [, , ,] = document.getElementsByTagName('div')

// e.g.
isEqualNode(, ) // false
isEqualNode(, ) // true
isEqualNode(, ) // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment