const selectors = [ '.addservice', '.addprice' ];
const data = Array.from(
document.querySelectorAll('.addserviceBlock'),
n => selectors.map(m => n.querySelector(m).value)
);
const headers = document.querySelectorAll('section > h2');
const menu = document.querySelector('что здесь должно быть, понятия не имею, сами разберётесь');
menu.innerHTML = Array
.from(headers, n => `<a href="#${n.parentNode.id}">${n.innerHTML}</a>`)
.join('');
for (const { parentNode: p, textContent: t } of headers) {
menu.insertAdjacentHTML(
'beforeend',
'<a href="#' + p.getAttribute('id') + '">' + t + '</a>'
);
}
menu.append(...Array.prototype.map.call(headers, n => {
const a = document.createElement('a');
a.href = '#'.concat(n.parentNode.attributes.id.value);
a.innerText = n.innerText;
return a;
}));
const wrapper = document.createElement('div');
const start = block.querySelector('.start');
for (let el; !(el = start.nextElementSibling).matches('.end'); wrapper.appendChild(el)) ;
start.insertAdjacentElement('afterend', wrapper);
const wrapper = document.createElement('div');
const children = [...block.children];
const iStart = children.findIndex(n => n.classList.contains('start'));
const iEnd = children.findIndex(n => n.classList.contains('end'));
wrapper.append(...children.slice(iStart + 1, iEnd));
children[iStart].after(wrapper);
data.reduce((acc, { unique, id, count, name }) => (
((acc[unique] ??= { count })[id] ??= []).push(name),
acc
), {})
function chunked(str, numChunks) {
const chunkSize = Math.ceil(str.length / numChunks);
return Array.from(
{ length: numChunks },
(n, i) => str.slice(i * chunkSize, (i + 1) * chunkSize)
);
}
function chunked(str, numChunks) {
return str.match(RegExp(`.{1,${Math.ceil(str.length / numChunks)}}`, 'g'));
}
function chunked(str, numChunks) {
return str.split(RegExp(`(.{${Math.ceil(str.length / numChunks)}})`)).filter(Boolean);
}
неаккуратненько как-то:
chunked('test', 3) // [ "te", "st", "" ]
const chunked = (str, numChunks) =>
numChunks <= str.length
? Array.from(
{ length: numChunks },
function(n, i) {
return str.slice(i * this, i === numChunks - 1 ? str.length : (i + 1) * this);
},
str.length / numChunks | 0
)
: 'извини, столько непустых кусков нарезать нельзя';
function chunked(str, numChunks) {
const chunkSize = str.length / numChunks | 0;
const numLooseItems = str.length % numChunks;
return Array.from(
{ length: numChunks },
function(_, i) {
return str.slice(this(i), this(i + 1));
},
i => i * chunkSize + Math.min(i, numLooseItems)
);
}
const newStr = str.replace(/\d.*/, '');
// или
const newStr = str.match(/^\D*/)[0];
// или
const newStr = str.split(/[0-9]/).shift();
// или
const newStr = str.slice(0, str.search(/\d|$/));
// или
const newStr = /[^\d]*/.exec(str).pop();
// или
const newStr = [...str].reduceRight((acc, n) => '0123456789'.includes(n) ? '' : acc + n, '');
const sectionAttribute = element.getAttribute('data-content')
const titles = document.querySelectorAll('[data-title]');
const contents = document.querySelectorAll('[data-content]');
titles.forEach(n => n.addEventListener('click', onClick));
function onClick({ currentTarget: t }) {
titles.forEach(n => n.classList.toggle('active', n === t));
contents.forEach(n => n.hidden = n.dataset.content !== t.dataset.title);
}
Object.values(arr.reduce((acc, { name, ...n }) => (
Object.values(n).find(Array.isArray)?.forEach(({ scores, channel }) =>
scores.forEach(({ score }) =>
(acc[channel]?.score > score) || (acc[channel] = { channel, name, score })
)
),
acc
), {}))
const payload = {
data: Object.fromEntries([
'раз свойство',
'два свойство',
'три свойство',
].map(n => [ n, this[n] ])),
};
new MutationObserver((mutations, observer) => {
if (mutations[0].target.classList.contains('интересующий-вас-класс')) {
observer.disconnect();
typed.start();
}
}).observe(элементНаличиеКлассаУКоторогоНадоОтследить, { attributes: true });
const getTheNearestLocation = (locations, [ x, y ]) =>
locations.reduce((nearest, n) => {
const d = ((n[1][0] - x) ** 2 + (n[1][1] - y) ** 2) ** 0.5;
return nearest[1] < d ? nearest : [ n, d ];
}, [ null, Infinity ])[0];
const parent = document.querySelector('ul');
const id = 'item';
const elems = Array.from(parent.children);
const index = elems.findIndex(n => n.id === id);
const result = index === -1 ? elems : elems.slice(0, index);
// или
const result = [...parent.querySelectorAll(`:not(#${id}, #${id} ~ *)`)];
// или
const result = [];
for (
let el = parent.firstElementChild;
el && el.id !== id;
el = el.nextElementSibling
) {
result.push(el);
}
const makeCensored = (str, words, replacement = '***') =>
str
.split(' ')
.map(n => words.includes(n) ? replacement : n)
.join(' ');
const group = (arr, idKey, valKey) =>
Object.values(arr.reduce((acc, { [idKey]: id, [valKey]: val }) => (
(acc[id] ??= { [idKey]: id, [valKey]: [] })[valKey].push(val),
acc
), {}));
const result = group(data, 'id', 'color');
str.split(';').pop()
// или
str.replace(/.*;/, '')
// или
str.match(/;(.*)/)[1]
// или
/[^;]+$/.exec(str).shift()
// или
str.slice(str.lastIndexOf(';') + 1)
// или
[...str].reduce((acc, n) => n === ';' ? '' : acc + n)
// или
Array.from(str).filter((n, i, a) => !a.includes(';', i)).join('')
const newArr = arr.map(function(n) {
return [ ...n, ...Array(this - n.length).fill('') ];
}, Math.max(...arr.map(n => n.length)));
const max = arr.reduce((max, { length: n }) => max > n ? max : n, 0);
arr.forEach(n => n.push(...Array(max - n.length).fill('')));