30 秒代码

coderljw 2024-10-13 30 秒代码
  • 30秒代码
  • JS
大约 5 分钟

# 1. 写入 JSON

const fs = require('fs')

const JSONToFile = (obj, filename) =>
  fs.writeFileSync(`${filename}.json`, JSON.stringify(obj, null, 2))

JSONToFile({ test: 'is passed' }, 'testJsonFile')
1
2
3
4
5
6

# 2. 浏览器端生成 UUID

const UUIDGeneratorBrowser = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  )

UUIDGeneratorBrowser()
1
2
3
4
5
6
7
8
9

# 3. Fibonacci 列表

const accumulate = (...nums) =>
  nums.reduce((acc, n) => [...acc, n + +acc.slice(-1)], [])

accumulate(...new Array(100).fill('').map((item, index) => index + 1))
1
2
3
4

# 4. 单词首字母大写

const capitalizeEveryWord = str =>
  str.replace(/\b[a-z]/g, char => char.toUpperCase())

capitalizeEveryWord('hello world!')
1
2
3
4

# 5. 摄氏度转华氏度

const celsiusToFahrenheit = degrees => 1.8 * degrees + 32

celsiusToFahrenheit(33)
1
2
3

# 6. 华氏度转换摄氏度

const fahrenheitToCelsius = degrees => ((degrees - 32) * 5) / 9

fahrenheitToCelsius(32)
1
2
3

# 7. 克隆正则

const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags)

const regExp = /lorem ipsum/gi
const regExp2 = cloneRegExp(regExp)
1
2
3
4

# 8. 过滤数组 | 对象中的空值

const compactObject = val => {
  const data = Array.isArray(val) ? val.filter(Boolean) : val
  return Object.keys(data).reduce(
    (acc, key) => {
      const value = data[key]
      if (Boolean(value))
        acc[key] = typeof value === 'object' ? compactObject(value) : value
      return acc
    },
    Array.isArray(val) ? [] : {}
  )
}

const obj = {
  a: null,
  b: false,
  c: true,
  d: 0,
  e: 1,
  f: '',
  g: 'a',
  h: [null, false, '', true, 1, 'a'],
  i: { j: 0, k: false, l: 'a' },
}
compactObject(obj)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 9. 复制内容至剪切板

const copyToClipboard = str => {
  const el = document.createElement('textarea')
  el.value = str
  el.setAttribute('readonly', '')
  el.style.position = 'absolute'
  el.style.left = '-9999px'
  document.body.appendChild(el)
  const selected =
    document.getSelection().rangeCount > 0
      ? document.getSelection().getRangeAt(0)
      : false
  el.select()
  document.execCommand('copy')
  document.body.removeChild(el)
  if (selected) {
    document.getSelection().removeAllRanges()
    document.getSelection().addRange(selected)
  }
}

copyToClipboard('Lorem ipsum')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 10. 复制内容至剪切板 (新 API)

var data = new DataTransfer()
data.items.add('Howdy, partner!', 'text/plain')
data.items.add('<b>Howdy</b>, partner!', 'text/html')
navigator.clipboard.write(data)

navigator.clipboard.writeText('some text')
1
2
3
4
5
6

# 11. 计算元素在数组中出现的次数

const countBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => {
    acc[val] = (acc[val] || 0) + 1
    return acc
  }, {})

countBy([6.1, 4.2, 6.3], Math.floor)
countBy(['one', 'two', 'three'], 'length')
countBy([{ count: 5 }, { count: 10 }, { count: 5 }], x => x.count)

const frequencies = arr =>
  arr.reduce((a, v) => {
    a[v] = a[v] ? a[v] + 1 : 1
    return a
  }, {})

frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b'])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 12. 获取星期

const dayName = (date, locale) =>
  date.toLocaleDateString(locale, { weekday: 'long' })

dayName(new Date())
dayName(new Date('09/23/2020'), 'de-DE')
1
2
3
4
5

# 13. 获取当前为今年的第几天

const dayOfYear = date =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)

dayOfYear(new Date())
1
2
3
4

# 14. 获取当前过去 | 未来 n 天数的时间

const daysAgo = n => {
  let d = new Date()
  d.setDate(d.getDate() - Math.abs(n))
  return d.toISOString().split('T')[0]
}

const daysFromNow = n => {
  let d = new Date()
  d.setDate(d.getDate() + Math.abs(n))
  return d.toISOString().split('T')[0]
}

daysAgo(20)
daysFromNow(5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 15. 深度冻结对象

const deepFreeze = obj => {
  Object.keys(obj).forEach(prop => {
    if (typeof obj[prop] === 'object') deepFreeze(obj[prop])
  })
  return Object.freeze(obj)
}

;('use strict')

const val = deepFreeze([1, [2, 3]])

val[0] = 3 // not allowed
val[1][0] = 4
1
2
3
4
5
6
7
8
9
10
11
12
13

# 16. 判端桌面端与移动端

const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
    ? 'Mobile'
    : 'Desktop'

detectDeviceType()
1
2
3
4
5
6
7
8

# 17. 数字分割

7777777..toLocaleString('en-US')

'7777777'.replace(/(?=(\B)(\d{3})+$)/g, ',')
1
2
3

# 18. 提取域名

const getBaseURL = url => url.replace(/[?#].*$/, '')

getBaseURL('http://url.com/page?name=Adam&surname=Smith')
1
2
3

# 19. 提取当前时间

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8)

getColonTimeFromDate(new Date())
1
2
3

# 20. 计算时间差

const getMonthsDiffBetweenDates = (dateInitial, dateFinal) =>
  Math.max(
    (dateFinal.getFullYear() - dateInitial.getFullYear()) * 12 +
      dateFinal.getMonth() -
      dateInitial.getMonth(),
    0
  )

getMonthsDiffBetweenDates(new Date('2017-12-13'), new Date('2018-04-29'))

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600 * 24)

getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22'))

const getHoursDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600)

getHoursDiffBetweenDates(
  new Date('2021-04-24 10:25:00'),
  new Date('2021-04-25 10:25:00')
)

const getMinutesDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 60)

getMinutesDiffBetweenDates(
  new Date('2021-04-24 01:00:15'),
  new Date('2021-04-24 02:00:15')
)

const getSecondsDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / 1000

getSecondsDiffBetweenDates(
  new Date('2020-12-24 00:00:15'),
  new Date('2020-12-24 00:00:17')
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

# 21. 生成 hash

const hashBrowser = val =>
  crypto.subtle
    .digest('SHA-256', new TextEncoder('utf-8').encode(val))
    .then(h => {
      let hexes = [],
        view = new DataView(h)
      for (let i = 0; i < view.byteLength; i += 4)
        hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8))
      return hexes.join('')
    })

hashBrowser(
  JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })
).then(console.log)
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 22. 判断是否为绝对路径

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str)

isAbsoluteURL('https://google.com')
isAbsoluteURL('ftp://www.myserver.net')
isAbsoluteURL('/foo/bar')
1
2
3
4
5

# 23. 判断是否为闰年

const isLeapYear = year => new Date(year, 1, 29).getMonth() === 1

isLeapYear(2019)
isLeapYear(2020)
1
2
3
4

# 24. 手机号隐藏中间四位

'17777777777'.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
1

# 25. 提取 url 请求参数

const queryStringToObject = url =>
  [...new URLSearchParams(url.split('?')[1])].reduce(
    (a, [k, v]) => ((a[k] = v), a),
    {}
  )

queryStringToObject('https://google.com?page=1&count=10')
1
2
3
4
5
6
7

# 26. 生成随机颜色

const randomHexColorCode = () => {
  let n = (Math.random() * 0xfffff * 1000000).toString(16)
  return '#' + n.slice(0, 6)
}

randomHexColorCode()
1
2
3
4
5
6

# 27. 读取 txt 文件每行数据

const fs = require('fs')

const readFileLines = filename =>
  fs
    .readFileSync(filename)
    .toString('UTF8')
    .split('\n')

readFileLines('test.txt')
1
2
3
4
5
6
7
8
9

# 28. 每帧动画执行回调函数

const recordAnimationFrames = (callback, autoStart = true) => {
  let running = false,
    raf
  const stop = () => {
    if (!running) return
    running = false
    cancelAnimationFrame(raf)
  }
  const start = () => {
    if (running) return
    running = true
    run()
  }
  const run = () => {
    raf = requestAnimationFrame(() => {
      callback()
      if (running) run()
    })
  }
  if (autoStart) start()
  return { start, stop }
}

const cb = () => console.log('Animation frame fired')
const recorder = recordAnimationFrames(cb)
recorder.stop()
recorder.start()
const recorder2 = recordAnimationFrames(cb, false)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# 29. 去除 HTML/XML 标签

const stripHTMLTags = str => str.replace(/<[^>]*>/g, '')

stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>')
1
2
3

# 30. 转小驼峰

const toCamelCase = str => {
  let s =
    str &&
    str
      .match(
        /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g
      )
      .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
      .join('')
  return s.slice(0, 1).toLowerCase() + s.slice(1)
}

toCamelCase('some_database_field_name')
toCamelCase('Some label that needs to be camelized')
toCamelCase('some-javascript-property')
toCamelCase('some-mixed_string with spaces_underscores-and-hyphens')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 31. 神奇的 Intl

new Intl.DateTimeFormat('zh-CN', {
  year: 'numeric',
  month: '2-digit',
  weekday: 'long',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: false,
})
  .format(new Date())
  .replace(/星期[^]?/, ' ')

new Intl.NumberFormat('zh-CN').format(1234567890)

new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec').format(1234567890)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 32. 反转义 HTML

const unescapeHTML = str =>
  str.replace(
    /&amp;|&lt;|&gt;|&#39;|&quot;/g,
    tag =>
      ({
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&#39;': "'",
        '&quot;': '"',
      }[tag] || tag)
  )

unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
'google'.link('https://www.google.com')
1

# 34. sleep 函数

// while
const sleep = delay => {
  const start = Date.now()
  while (Date.now() < start + delay) continue
}

// Promise
const sleep = delay => new Promise(resolve => setTimeout(resolve, delay))
1
2
3
4
5
6
7
8

# 35. 伞兵

(!~+[] + {})[--[~+''][+[]] * [~+[]] + ~~!+[]] + ({} + [])[[~!+[]] * ~+[]]
1
以父之名
周杰伦.mp3