const columnIndex = {
color: 0,
fruit: 1,
};
function filter() {
const filters = Object.entries(Array
.from(document.querySelectorAll('.list-group :checked'))
.reduce((acc, n) => ((acc[n.name] ??= []).push(n.value), acc), {})
);
document.querySelectorAll('table tbody tr').forEach(n => {
n.style.display = filters.some(([ k, v ]) => !v.includes(n.cells[columnIndex[k]].innerText))
? 'none'
: 'block';
});
}
document.querySelectorAll('.list-group').forEach(n => n.addEventListener('change', filter));
function getDays(year, month) {
const days = [];
const d = new Date(year, month, 1);
let week = 1;
while (d.getMonth() === month) {
const date = d.getDate();
const day = d.getDay();
days.push({
day: date,
weeknumber: (day === 1 || date === 1) ? week : false,
weekday: d.toLocaleString('en-US', { weekday: 'short' }),
});
d.setDate(date + 1);
week += !day;
}
return days;
}
text.match(RegExp(str, 'g'))?.length ?? 0
text.split(str).length - 1
const flatObj = obj =>
Object.entries(obj).reduce((acc, [ k, v ]) => (
v instanceof Object && !Array.isArray(v)
? Object.assign(acc, flatObj(v))
: acc[k] = v,
acc
), {});
document.querySelectorAll('h2').forEach(n => {
const [ season, , episode ] = n.innerText.split(' ');
if (+episode === 1) {
n.id = `season-${season}`;
}
});
[...document.querySelectorAll('h2')]
.filter(n => n.innerText.endsWith(', 1 серия'))
.forEach((n, i) => n.id = `season-${i + 1}`);
document.querySelectorAll('h2').forEach((n, i, a) => {
const prev = i && a[i - 1].innerText.match(/\d+/)[0];
const curr = n.innerText.match(/\d+/)[0];
if (curr !== prev) {
n.id = `season-${curr}`;
}
});
Array
.from(document.querySelectorAll('h2'))
.reduce((acc, n) => (acc[parseInt(n.innerText)] ??= n, acc), [])
.forEach((n, i) => n.id = `season-${i}`);
const transpose = matrix => Array.from(
{ length: matrix[0]?.length ?? 0 },
(_, i) => matrix.map(n => n[i])
);
function transpose(matrix) {
const result = Array(matrix.length && matrix[0].length);
for (let i = 0; i < result.length; i++) {
result[i] = [];
for (let j = 0; j < matrix.length; j++) {
result[i][j] = matrix[j][i];
}
}
return result;
}
const groupAdjacent = (arr, newGroup) =>
arr.reduce((acc, n, i, a) => (
(!i || newGroup(n, a[~-i])) && acc.push([]),
acc[~-acc.length].push(n),
acc
), []);
const result = groupAdjacent(arr, (c, p) => c !== -~p);
function group(data, key) {
const grouped = new Map;
let i = -1;
for (const n of data) {
const k = key(n, ++i);
grouped.set(k, grouped.get(k) ?? []).get(k).push(n);
}
return grouped;
}
const result = [...group(arr, (n, i) => n - i).values()];
$('.js-cropped-word').text((i, text) => text.replace(/(?<=\S{19,}).+/, '...'));
В Сафари не работает
document.querySelectorAll('.js-cropped-word').forEach(n => {
n.textContent = n.textContent.replace(/(\S{19}).+/, '$1...');
});
const max = 19;
for (const n of document.getElementsByClassName('js-cropped-word')) {
const words = n.innerText.split(' ');
const i = words.findIndex(n => n.length > max);
if (i !== -1) {
words.length = i + 1;
words[i] = words[i].slice(0, max) + '...';
n.innerText = words.join(' ');
}
}
const elements = document.querySelectorAll('input[type="button"]');
const wrapperTag = 'div';
const wrapperClass = 'block';
elements.forEach(n => {
const wrapper = document.createElement(wrapperTag);
n.replaceWith(wrapper);
wrapper.classList.add(wrapperClass);
wrapper.append(n);
});
for (const n of elements) {
n.after(document.createElement(wrapperTag));
n.nextSibling.className = wrapperClass;
n.nextSibling.appendChild(n);
}
for (let i = 0; i < elements.length; i++) {
const n = elements[i];
n.outerHTML = `<${wrapperTag} class="${wrapperClass}">${n.outerHTML}</${wrapperTag}>`;
}
(function wrap(i, n = elements[i]) {
if (n) {
const wrapper = document.createElement(wrapperTag);
n.parentNode.replaceChild(wrapper, n);
wrapper.classList.value = wrapperClass;
wrapper.insertAdjacentElement('afterbegin', n);
wrap(-~i);
}
})(0);
const values = [ '1', '2', '3' ];
[...selectEl].forEach(n => values.includes(n.value) && n.remove());
for (const n of selectEl.querySelectorAll(values.map(n => `[value="${n}"]`))) {
selectEl.removeChild(n);
}
for (let i = selectEl.options.length; i--;) {
const n = selectEl.options[i];
if (values.indexOf(n.value) !== -1) {
n.outerHTML = '';
}
}
calc__price
и calc__payment
заменить на общий calc
.const $price = $('#price');
const $firstPayment = $('#first-payment');
function update($elem) {
$elem.closest('.calc').find('output').text($elem.val());
$('.payment-percent').html(Math.round($firstPayment.val() * 100 / $price.val()) + '%');
}
$price.closest('.calc').on('input', function() {
const val = $price.val();
$firstPayment
.val((i, v) => Math.min(v, val))
.attr('max', val)
.rangeslider('update', true);
update($firstPayment);
});
$price.add($firstPayment)
.rangeslider({ polyfill: false })
.closest('.calc')
.on('input', e => update($(e.target)))
.end()
.trigger('input');
function walkNested(val, callback) {
callback(val);
if (val instanceof Object) {
Object.values(val).forEach(n => walkNested(n, callback));
}
}
walkNested(obj, n => n?.touched === true && (n.touched = false));
function walkNested(val, callback) {
for (const stack = [ val ]; stack.length;) {
const n = stack.pop();
callback(n);
stack.push(...Object.values(n ?? {}));
}
}
const keys = [ 'city', 'country' ];
.const newArr = arr.map(n => Object.fromEntries(Object.values(n).map((v, i) => [ keys[i], v ])));
arr.forEach(n => Object.entries(n).forEach(([ k, v ], i) => (delete n[k], n[keys[i]] = v)));
str.replace(/\t.*/s, '')
// или
str.match(/^[^\t]*/)[0]
// или
str.slice(0, str.search(/\t|$/))
// или
str.split('\t', 1).pop()
// или
[...str].reduceRight((acc, n) => n === '\t' ? '' : n + acc, '')
const $menuItems = $('#menu a');
$('#submenu > ul').width(i => $menuItems.eq(i).width());
const min = 7;
const max = min + 21;
function update(value) {
value = Math.max(min, Math.min(max, value | 0));
$('#spinner2').val(value);
$('#slider2').slider('value', value);
const date = new Date();
date.setDate(date.getDate() + value);
$('#amount').val(date.toLocaleString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}));
}
$('#slider2').slider({
range: 'min',
min,
max,
step: 1,
slide: (e, ui) => update(ui.value),
});
$('#spinner2').spinner({
min,
max,
spin: (e, ui) => update(ui.value),
}).on('input', e => update(e.target.value)).trigger('input');
const sort = {
number: (a, b) => a - b,
string: (a, b) => a.localeCompare(b),
};
function sortTable(table, colIndex) {
if (typeof table === 'string') {
table = document.querySelector(table);
}
const head = table.tHead.rows[0];
const compare = sort[head.cells[colIndex].dataset.type] ?? sort.string;
const value = row => row.cells[colIndex].innerText;
const tbody = table.tBodies[0];
tbody.append(...[...tbody.rows].sort((a, b) => compare(value(a), value(b))));
[...head.cells].forEach((n, i) => n.classList.toggle('sorted', i == colIndex));
}
.sorted {
background: #ccc;
}
.sorted::after {
content: " \2193";
}
// просто дёргаем сортировку
sortTable('#grid', 0);
sortTable(document.querySelector('table'), 1);
// или, сортируем по клику на заголовки столбцов
document.querySelectorAll('#grid th').forEach(function(n) {
n.addEventListener('click', this);
}, ({ target: t }) => sortTable(t.closest('table'), t.cellIndex));