Last active
February 11, 2021 14:55
-
-
Save kitcat-dev/c907d17dcda93bbb2615983d70e06119 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. Генерация случайного числа в заданном диапазоне | |
const randomNumberInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; | |
randomNumberInRange(10, 20) // 14 | |
// 2. Переключение логического значения | |
const toggle = value => !value | |
toggle(false) // true | |
// 3. Сортировка элементов массива в случайном порядке (осторожно! низкий уровень случайности) | |
const sortRandom = (arr) => arr.sort(() => Math.random() - 0.5) | |
sortRandom([1, 2, 3, 4, 5]) // [1, 4, 2, 5, 3] | |
// 4. Заглавная буква в строке | |
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1) | |
capitalize("hey, this is pretty cool!") // "Hey, this is pretty cool!" | |
// 5. Исключение hostname из URL | |
const extractHostname = (url) => { | |
let hostname = (url.indexOf("//") > -1) ? url.split('/')[2] : url.split('/')[0] | |
hostname = hostname.split(':')[0] // Remove port number. | |
hostname = hostname.split('?')[0] // Remove querystring. | |
return hostname | |
} | |
extractHostname(window.location.href) // gist.github.com | |
// 6. Получение уникальных значений из массива | |
const uniqueValues = (arr) => [...new Set(arr)] | |
uniqueValues([1, 2, 3, 1, 5, 2]) // [1, 2, 3, 5] | |
// 7. Проверка, соответствуют ли условию все элементы массива (или хотя бы один) | |
const isOldEnough = (age) => age >= 18 | |
const ages = [7, 19, 12, 33, 15, 49] | |
ages.every(isOldEnough) // false | |
ages.some(isOldEnough) // true | |
// 8. Форматирование чисел с плавающей точкой в зависимости от locale | |
const formatFloat = (floatValue, decimals) => parseFloat(floatValue.toFixed(decimals)).toLocaleString("en-US") | |
formatFloat(10000.245, 2) // "10,000.25" | |
formatFloat(10000.245, 0) // "10,000" | |
// 9. Обновление строки запроса | |
const searchParams = new URLSearchParams(window.location.search) | |
searchParams.set('key', 'value') | |
history.replaceState(null, null, '?' + searchParams.toString()) | |
// 10. Разрешены только положительные числа | |
const getPositiveNumber = (number) => Math.max(number, 0) | |
getPositiveNumber(-15) //0 | |
getPositiveNumber(15) // 15 | |
// 11. Копирование текста в буфер обмена | |
const copyTextToClipboard = (text) => { | |
return navigator.clipboard.writeText(text) | |
} | |
setTimeout(async () => { await copyTextToClipboard('hello world') }, 2000) | |
// 12. Сведение значений элементов массива к заданному типу | |
const arrayToNumbers = (arr) => arr.map(Number) | |
const arrayToBooleans = (arr) => arr.map(Boolean) | |
arrayToNumbers(['0', '1', '2', '3']) // [0, 1, 2, 3] | |
arrayToBooleans(['0', '1', '2', '3']) // [true, true, true, true] | |
arrayToBooleans([0, 1, '2', '3']) // [false, true, true, true] | |
// 13. Подсчет дней между двумя датами (date-fns is better) | |
const daysBetweenDates = (dateA, dateB) => { | |
const timeDifference = Math.abs(dateA.getTime() - dateB.getTime()) | |
// Seconds * hours * miliseconds | |
return Math.floor(timeDifference / (3600 * 24 * 1000)) | |
} | |
daysBetweenDates(new Date('2020/10/21'), new Date('2020/10/29')) // 8 | |
daysBetweenDates(new Date('2020/10/21'), new Date('2021/10/29')) // 373 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment