JavaScript là một trong những ngôn ngữ phổ biến nhất với giới lập trình. Có rất nhiều tài liệu tham khảo trên internet điều đó không có nghĩa chúng ta bị ám ảnh vì phải liên tục cập nhật liên tục nhiều hơn nữa vào các cơ sở mã của mình, Chúng ta chỉ cần thêm tiện ích mà chúng ta có thể xây dựng lên.
const randomString = () => Math.random().toString(36).slice(2)randomString() // gi1qtdego0b
randomString() // f3qixv40mot
randomString() // eeelv1pm3ja
const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]))escape('<div class="medium">Hi Medium.</div>')
// <div class="medium">Hi Medium.</div>
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())uppercaseWords('hello world'); // 'Hello World'
Cảm ơn Christopher Strolia-Davis vì đây là cách dễ dàng hơn mà anh ấy đưa ra.const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));toCamelCase('background-color'); // backgroundColor
toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
toCamelCase('_hello_world'); // HelloWorld
toCamelCase('hello_world'); // helloWorld
const removeDuplicates = (arr) => [...new Set(arr)]console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]))
// [1, 2, 3, 4, 5, 6]
const flat = (arr) =>
[].concat.apply(
[],
arr.map((a) => (Array.isArray(a) ? flat(a) : a))
)// Or
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']
const removeFalsy = (arr) => arr.filter(Boolean)removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])
// ['a string', true, 5, 'another string']
const isEven = num => num % 2 === 0isEven(2) // true
isEven(1) // false
const random = (min, max) => Math.floor (Math.random () * (max - min + 1) + min)random (1, 50) // 25
random (1, 50) // 34
const Average = (... args) => args.reduce ((a, b) => a + b) / args.length;trung bình (1, 2, 3, 4, 5); // 3
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)round(1.005, 2) //1.01
round(1.555, 2) //1.56
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));diffDays(new Date("2021-11-3"), new Date("2022-2-1")) // 90
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))dayOfYear(new Date()) // 74
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`randomColor() // #9dae4f
randomColor() // #6ef10e
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)rgbToHex(255, 255, 255) // '#ffffff'
const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)))
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
[foo, bar] = [bar, foo]
const pause = (millis) => new Promise(resolve => setTimeout(resolve, millis))const fn = async () => {
await pause(1000) console.log('fatfish') // 1s later
}
fn()
Trên đây là tất cả thủ thuật one-line code mà chúng tôi chia sẻ hôm nay. Cảm ơn bạn đã đọc bài! Hãy trở thành chuyên gia lập trình với 18 bước JavaScript One-Liners.