const container = document.querySelector('.buttons');
const buttonSelector = '.button';
const onButtonClick = button => console.log(button.id);container.addEventListener('click', e => {
const button = e.target.closest(buttonSelector);
if (button) {
onButtonClick(button);
}
});container.querySelectorAll(buttonSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => onButtonClick(e.currentTarget));
Например если число 200000
const bullshitDateFormat = str =>
new Date(+str.replace(/\D/g, ''))
.toLocaleString('ru-RU')
.slice(0, -3)
.replace(',', '');.slice(0, -3) выглядит сильно так себе (с другой стороны - коротко), вместо него можно в явном виде (второй параметр) указать при вызове toLocaleString, какие элементы даты надо получить:{
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}
const getName = n => n.name.split(' ').pop();
// или
const getName = n => n.name.replace(/.+ /, '');
// или
const getName = n => n.name.match(/\S*$/)[0];
// или
const getName = n => n.name.slice(-~n.name.lastIndexOf(' '));const result = Object.values(arr.reduce((min, n) => {
const name = getName(n);
min[name] = +min[name]?.price < +n.price ? min[name] : n;
return min;
}, {}));function group(data, key, val = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const getVal = val instanceof Function ? val : n => n[val];
const result = new Map;
for (const n of data) {
const k = getKey(n);
result.set(k, result.get(k) ?? []).get(k).push(getVal(n));
}
return result;
}
function max(data, key = n => n) {
const getVal = key instanceof Function ? key : n => n[key];
let result = null;
for (const n of data) {
const val = getVal(n);
result = result?.[1] >= val ? result : [ n, val ];
}
return result?.[0];
}const result = Array.from(
group(arr, getName).values(),
n => max(n, m => -m.price)
);
const result = arr.flat().map((n, i) => ({ ...n, id: -~i }));const result = [];
for (const n of arr) {
for (const m of n) {
result.push({
...m,
id: result.length + 1,
});
}
}
const coord = [ 0, 0 ];
const step = 10;
const moveFunc = e => {
const shift = ({
ArrowUp: [ 0, -1 ],
ArrowDown: [ 0, 1 ],
ArrowLeft: [ -1, 0 ],
ArrowRight: [ 1, 0 ],
})[e.code];
if (shift) {
div.style.left = `${coord[0] += shift[0] * step}px`;
div.style.top = `${coord[1] += shift[1] * step}px`;
}
};
const result = Array.from(
document.querySelectorAll('#spisok > div > p > br'),
n => n.nextSibling.textContent.trim()
);const result = Array.prototype.map.call(
document.getElementById('spisok').getElementsByTagName('button'),
n => n.previousSibling.nodeValue.replace(/(^\s+)|(\s+$)/g, '')
);
const makeOrderList = str =>
Object.fromEntries(Array.from(
str.matchAll(/(\d+) ([^,]+)/g),
n => [ n[2].replace(/ /g, '_'), +n[1] ]
));const makeOrderList = str => str
.split(', ')
.map(n => [ n.split(' ').slice(1).join('_'), parseInt(n) ])
.filter(n => !Number.isNaN(n[1]))
.reduce((acc, n) => (acc[n[0]] = n[1], acc), {});
const attrName = 'bst-click';
const elements = document.querySelectorAll(`[${attrName}]`);const data = Array.from(
elements,
n => [
n.attributes[attrName].value,
n.classList.value,
]
);const data = Array.prototype.reduce.call(
elements,
(acc, n) => (
(acc[n.getAttribute(attrName)] ??= []).push(n.className),
acc
),
{}
);
hrefs.filter(n => !/\.pdf$/.test(n))
// или
hrefs.filter(n => !n.endsWith('.pdf'))
// или
hrefs.filter(n => n.split('.').pop() !== 'pdf')
// или
hrefs.filter(n => n.lastIndexOf('.pdf') !== n.length - 4)
// или
hrefs.filter(n => n.slice(-4) !== '.pdf')
// или
hrefs.filter(n => n.replace(/.*\./, '') !== 'pdf')
// или
hrefs.filter(n => n.match(/\.[^.]+$/g) != '.pdf')
const getLast = (obj, parentName) =>
obj.next instanceof Object
? getLast(obj.next, obj.name)
: { ...obj, parentName };function getLast(obj) {
let parentName = void 0;
for (; obj.next; parentName = obj.name, obj = obj.next) ;
return { ...obj, parentName };
}
addEventListener в качестве третьего аргумента { once: true }.
$('#add-instr').click(function() {
$('#column-left').append(`
<article class="instruction">
<div class="name">
${$('#i-name').val()}
<button class="remove">x</button>
</div>
<div class="desc">
${$('#i-desc').val()}
</div>
</article>
`);
});
$('#column-left').on('click', '.remove', function() {
$(this).closest('.instruction').remove();
});
const count = (arr, val) => arr.filter(n => n === val).length;
// или
const count = (arr, val) => arr.reduce((acc, n) => acc + (n === val), 0);function Counter(data, key = n => n) {
const counted = new Map;
for (const n of data) {
const k = key(n);
counted.set(k, (counted.get(k) ?? 0) + 1);
}
return k => counted.get(k) ?? 0;
}const arr = [ 1, 1, NaN, 1, 2, NaN, 9, NaN, NaN, 9, 7, 'hello, world!!', 'hello, world!!' ];
const counted = Counter(arr);
console.log(counted(1)); // 3
console.log(counted(NaN)); // 4
console.log(counted('hello, world!!')); // 2
console.log(counted(10)); // 0const counted = Counter('hello, world!!');
console.log(counted('o')); // 2
console.log(counted('l')); // 3
console.log(counted('x')); // 0<span class="color">red</span>
<span class="color">green</span>
<span class="color">red</span>
<span class="color">red</span>const counted = Counter(document.querySelectorAll('.color'), el => el.innerText);
console.log(counted('red')); // 3
console.log(counted('blue')); // 0
const sortedElements = [...elements].sort((a, b) =>
+a.relations.includes(b.id) ||
-b.relations.includes(a.id) ||
a.name.localeCompare(b.name)
);
<a data-problem="value1">
<a data-problem="value2"><a data-problem="value1|value2">$('.problem').change(function() {
const problems = $(':checked', this)
.get()
.map(({ dataset: { type, problem } }) => ({ type, problem }));
$(this)
.closest('.remont')
.find('.price__item')
.hide()
.filter((i, { dataset: d }) =>
problems.some(p => d.type === p.type && d.problem.includes(p.problem))
)
.show();
}).change();
$('.problem').change(({ target: t }) => {
const attrsSelector = [ 'type', 'problem' ]
.map(n => `[data-${n}="${t.dataset[n]}"]`)
.join('');
$(`.price-problem ${attrsSelector}`).toggle(t.checked);
}).find('input').change();
$('.item img').wrap(function() {
return '<a href="' + $(this).attr('src') + '"></a>';
});document.querySelectorAll('.item img').forEach(n => {
n.outerHTML = `<a href="${n.attributes.src.value}">${n.outerHTML}</a>`;
});for (const n of document.querySelectorAll('.item img')) {
const a = document.createElement('a');
a.href = n.getAttribute('src');
n.after(a);
a.append(n);
}