Skip to content

Instantly share code, notes, and snippets.

@chrisryana
Last active June 16, 2020 10:45
Show Gist options
  • Select an option

  • Save chrisryana/ad289dee38f58af9516d733db4f5a4b0 to your computer and use it in GitHub Desktop.

Select an option

Save chrisryana/ad289dee38f58af9516d733db4f5a4b0 to your computer and use it in GitHub Desktop.
Простые но полезные функции на js
// Принимает целое число и массив склонений, выдает правильное числительное = (N, ['час', 'часа', 'часов'])
function declOfNum(n, titles) {
return titles[
n % 10 === 1 && n % 100 !== 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
];
}
// Делит целое число на разряды пробелом
function numberWithSpaces(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}
// Тоже самое, но для чисел с плавающей точкой
function numberWithSpaces(x) {
const parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
return parts.join(".");
}
// Возвращает новый объект без переданного ключа
const removeProperty = prop => ({ [prop]: _, ...rest }) => rest
// Находит ширину полосы прокрутки в браузере
function getScrollWidth() {
const div = document.createElement('div');
div.style.overflowY = 'scroll';
div.style.width = '50px';
div.style.height = '50px';
document.body.append(div);
const scrollWidth = div.offsetWidth - div.clientWidth;
div.remove();
return scrollWidth;
}
// Удаляет пробелы только в начале или конце строки
function trimString(value) {
// start
value.replace(/^\s+/g, '');
// end
value.replace(/\s+$/g, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment