Сниппеты JavaScript. Часть 1
Число
Решение проблемы чисел с плавающей точкой
console.log(0.1 + 0.2 === 0.3) // false
const areEqual = (x, y) => x - y < Number.EPSILON
const result = 0.1 + 0.2
if (areEqual(result, 0.3)) {
console.log('0.1 + 0.2 = 0.3') // 0.1 + 0.2 = 0.3
}
Четность/нечетность числа
const oddOrEven = (n) => (n % 2 === 0 ? 'even' : 'odd')
// or
const oddOrEven = (n) => (n & 1 ? 'odd' : 'even')
Находится ли число в указанном диапазоне?
const isInRange = (n, start, end = null) => {
if (end && start > end) [end, start] = [start, end]
return end === null ? n >= 0 && n < start : n >= start && n < end
}
isInRange(2, 0, 10) // true
isInRange(2, 3, 9) // false
Округление числа до указанного количества знаков после запятой
const round = (n, d = 0) => +`${Math.round(`${n}e${d}`)}e-${d}`
Арифметическая прогрессия
const arithmeticProgress = (n, max) =>
Array.from({ length: Math.ceil(max / n) }, (_, i) => (i + 1) * n)
Геометрическая прогре ссия
const geometricProgress = (end, start = 1, step = 2) =>
Array.from({ length: ~~(Math.log(end / start) / Math.log(step)) + 1 }).map(
(_, i) => start * step ** i
)
Наибольший общий делитель
const gcd = (...nums) => {
const _gcd = (x, y) => (!y ? x : gcd(y, x % y))
return nums.reduce((a, b) => _gcd(a, b))
}
Наименьшее общее кратное
const lcm = (...nums) => {
const gcd = (x, y) => (!y ? x : gcd(y, x % y))
const _lcm = (x, y) => (x * y) / gcd(x, y)
return nums.reduce((a, b) => _lcm(a, b))
}
Преобразование арабских чисел в римские
const convertToRoman = (n) => {
const lookup = [
['M', 1000],
['CM', 900],
['D', 500],
['CD', 400],
['C', 100],
['XC', 90],
['L', 50],
['XL', 40],
['X', 10],
['IX', 9],
['V', 5],
['IV', 4],
['I', 1]
]
return lookup.reduce((a, [k, v]) => {
a += k.repeat(~~(n / v))
n = n % v
return a
}, '')
}
Среднее значение
const average = (...nums) => nums.reduce((a, c) => a + c, 0) / nums.length
Случайное целое число в заданном диапазоне
const getRandomInt = (min, max) => ~~(min + Math.random() * (max - min + 1))