Less is more
目录
const toggle = (value) => value = !value
const randomNumberInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const getPositiveNumber = (number) => Math.max(number, 0)
- const isEven = num => num % 2 === 0;
- console.log(isEven(2)); // True
- const average = (...args) => args.reduce((a, b) => a + b) / args.length;
- average(1, 2, 3, 4); // 2.5
- const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
- toFixed(25.198726354, 6); // 25.198726
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1)
- const randomString = () => Math.random().toString(36).slice(2);
- randomString();
- const reverse = str => str.split('').reverse().join('');
- reverse('hello world'); // 'dlrow olleh'
const isArray = (arr) => Array.isArray(arr)
const sortRandom = (arr) => arr.sort(() => Math.random() - 0.5)
const uniqueValues = (arr) => [...new Set(arr)]
- const isOldEnough = (age) => age >= 18
- const olderPeople = [39, 51, 33, 65, 49]
- olderPeople.every(isOldEnough) // true
-
- // every 方法检查数组中的所有项是否满足某个条件
- // some() 方法检查数组中的一个元素来满足某个条件
- const arrayToNumbers = (arr) => arr.map(Number)
- const numbers = arrayToNumbers(['0', '1', '2', '3'])
- const arrayToBooleans = (arr) => arr.map(Boolean)
- const booleans = arrayToBooleans(numbers)
- const intersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)))
- intersection([1, 2, 3], [2, 3, 4, 7, 8], [1, 3, 9]) // [3]
- const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
- isNotEmpty([1, 2, 3]); // true
Object.fromEntries(new URLSearchParams(window.location.search))
const showPrintDialog = () => window.print()
- const copyTextToClipboard = async (text) => {
- await navigator.clipboard.writeText(text)
- }
- const daysBetweenDates = (dateA, dateB) => {
- const timeDifference = Math.abs(dateA.getTime() - dateB.getTime())
- return Math.floor(timeDifference / (3600 * 24 * 1000))
- }
- daysBetweenDates(new Date('2020/10/21'), new Date('2021/10/29')) // 373
- const isWeekday = (date) => date.getDay() % 6 !== 0;
- console.log(isWeekday(new Date(2021, 0, 10))); // false (Sunday)
- const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
- isDateValid("December 17, 1995 03:24:00"); // true
- const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
- dayOfYear(new Date()); // 272
- const daysInMonth = (month, year) => new Date(year, month, 0).getDate()
- daysInMonth(2, 2024) // 29
- let personA = "Laura"
- let personB = "John"
- [personA, personB] = [personB, personA]
- const replaceSpaces = (str) => str.replace(/\s\s+/g, ' ')
- replaceSpaces('Too many spaces') // 'Too many spaces'
- const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]))
- isEqual({ name: 'Frank', age: 32 }, { name: 'Frank', age: 32 }, { name: 'Frank', age: 32 }) // true
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
- // 获取浏览器Cookie的值
- const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
- cookie('xx');
-
- // 清除全部Cookie
- const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
- const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
- rgbToHex(0, 51, 255); // #0033ff
- const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
- console.log(randomHex());
- const goToTop = () => window.scrollTo(0, 0);
- goToTop();
- const getSelectedText = () => window.getSelection().toString();
- getSelectedText();
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
const elementIsInFocus = (el) => (el === document.activeElement);
- const touchSupported = () => {
- ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
- }
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
未完待续。。。