残業を減らして恋人と過ごす時間を増やすため、私はBATのお偉方たちに懇願して、JSの15の秘訣を教えてもらいました。
メインテキスト
ターゲット配列に最も近い日付配列の添え字を返します。
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()
const dates = [
new Date(),
new Date(),
new Date(),
]
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(),
new Date(),
new Date(),
]
getMinDate(dates) // T.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() // クロームの新しいバージョンではtrue、Firefoxではfalse。
url が
const isUrl = str => /^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$/.test(str)
// e.g.
isUrl('https://..om') // true
isUrl('https://ww') // false
絵文字かどうかの判定
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 getLevel = (value = 0, ratio = 50, levels = '1、2、3、4、5') => {
if (typeof value !== 'number') {
throw new Error('Argument must be a number')
}
const levelHash = '1、2、3、4、5'.split('')
const max = levelHash[levelHash.length - 1]
return levelHash[Math.floor(value / ratio)] || max
}
// e.g.
getLevel1(0) //
getLevel1(40) //
getLevel(77) //
イベントシミュレーションのトリガー
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)
// このとき、携帯端末の下で指をスライドさせるとクリックイベントが発生する
domが等しいかどうかの判定
const isEqualNode = (dom1, dom2) => dom1.isEqualNode(dom2)
/*
<div>これは最初のdivである</div>
<div>これは2番目のdivである</div>
<div>これは最初のdivである</div>
*/
const [1、2、3,] = document.getElementsByTagName('div')
// e.g.
isEqualNode(one, two) // false
isEqualNode(i, iii) // true
isEqualNode(ii, iii) // false
マルチプロパティ双方向バインディング
/*
<div id="box" class="box" style="border: 1px solid; width: 100px; height: 100px;"></div>
<output id="ouput" name="output"></output>
*/
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)
// 入力の対応するプロパティが変更されると、出力テキストが変更された内容に変更される。
指定範囲内の乱数を取得
const getRandom = (min = 0, max = 100) => {
if (typeof min !== 'number' || typeof max !== '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
ファイルサイズのフォーマット
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('') // 9.77MB
配列の前後の要素数を取得します。
const arrayRange = (array, index, distance = '+') => {
if (!Array.isArray(array) || typeof index !== '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, '-') // ["a"]
追記
以上の15個のJSのコツは、魚頭さんが数少ない大手工場の達人から膝を突き合わせて苦労して手に入れたものなので、ぜひ皆さんのビジネスで有効に活用して、残業時間を減らしてください。





