const SHOW_ON_LOAD = 3;
const SHOW_MORE = 2;
const items = [...document.querySelectorAll('.box-list__item')];
const button = document.querySelector('.show-more');
showItems(SHOW_ON_LOAD);
button.addEventListener('click', () => showItems(SHOW_MORE));
function showItems(count) {
items.splice(0, count).forEach(n => n.classList.add('ui-box-active'));
button.classList.toggle('ui-button-hidden', !items.length);
}
openItems.forEach(function (formItem) {
formItem.addEventListener('click', function () {
openBtn.innerText = this.innerText;
openList.classList.remove('open');
hiddenInput.value = this.dataset.value;
});
});
openList.addEventListener('click', function(e) {
const item = e.target.closest('li.form-item');
if (item) {
openBtn.innerText = item.innerText;
openList.classList.remove('open');
hiddenInput.value = item.dataset.value;
}
});
const newData = data.map((n, i, a) => ({
...n,
newSick: n.sick - (i < ~-a.length && a[-~i].sick),
}));
data.forEach((n, i, a) => n.newSick = n.sick - (a[i + 1]?.sick ?? 0));
// или
data.reduceRight((prev, n) => (n.newSick = n.sick - prev, n.sick), 0);
const sorted = (arr, key) => arr
.map(n => [ key(n), n ])
.sort(([a], [b]) => a < b ? -1 : +(a > b))
.map(n => n[1]);
const sortedArr = sorted(arr, n => n[0].replace(/^\D+/, ''));
const sortedArr = sorted(arr, n => {
const d = n[0].match(/\d+/g);
return +d[0] + +d.at(-1);
});
let count = 0;
const countEl = document.querySelector('.text');
const buttons = [...document.querySelectorAll('.click')];
const onClick = e => updateCount(e.target.classList.toggle('clicked') ? 1 : -1);
const updateCount = change => countEl.innerText = count += change;
buttons.forEach(n => n.addEventListener('click', onClick));
updateCount(buttons.reduce((acc, n) => acc + n.classList.contains('clicked'), 0));
- document.querySelector('.calculate').addEventListener('click', function () {
+ document.querySelector('form').addEventListener('input', function () {
const result = Array
.from(letter, n => soundParts[Number.isNaN(+n) ? 'letter' : 'number'][n])
.filter(Boolean);
const result = Object
.entries(Object.assign({}, ...Object.values(soundParts)))
.reduce((acc, n) => (letter.includes(n[0]) && acc.push(n[1]), acc), []);
const groupAdjacent = (arr, newGroup) =>
arr.reduce((acc, n, i, a) => (
(!i || newGroup(n, a[~-i])) && acc.push([]),
acc.at(-1).push(n),
acc
), []);
const result = groupAdjacent(arr, (c, p) => c.name !== p.name);
for (let i in goods) { if (discounts.length === 0) { count = goods[i].value * goods[i].amount; } for (let j in discounts) { if (goods[i].name === discounts[j].name) { count = (goods[i].value - goods[i].value * discounts[j].discount) * goods[i].amount; } else { count = goods[i].value * goods[i].amount; } } sum += count; console.log(count, goods[i].name); }
for (const n of goods) {
let s = n.value * n.amount;
for (const m of discounts) {
if (n.name === m.name) {
s *= 1 - m.discount;
break;
}
}
sum += s;
}
Возможно есть лучший способ для решения такой задачи.
function totalCost(goods, discounts) {
discounts = Object.fromEntries(discounts.map(n => [ n.name, 1 - parseFloat(n.discount) / 100 ]));
return goods.reduce((acc, n) => acc + n.value * n.amount * (discounts[n.name] ?? 1), 0);
}
Array.from(word.matchAll(/[aeiouy]/gi), n => n.index)
[...word.toLowerCase()].reduce((acc, n, i) => ('aeiouy'.includes(n) && acc.push(i), acc), [])
Object.entries(word).filter(n => 'AaEeIiOoUuYy'.indexOf(n[1]) !== -1).map(n => +n[0])
let letters = 'АаЕеIiOoUuYy' //Создал переменную со строкой с гласными
if (arg1[i] == letters[j]) { //Если элемент слова равен элементу строки с согласными newArr.push(arg1[i].indexOf()) //То пушу в массив индексы гласных этого слова }
.push(i)
.const className = 'some-link';
const colors = {
En: 'red',
Ru: 'green',
De: 'blue',
};
for (const n of document.getElementsByClassName(className)) {
n.style.color = colors[n.textContent];
}
document.querySelectorAll(`.${className}`).forEach(function(n) {
n.style.color = this.find(m => m[0].test(n.innerText))?.[1];
}, Object.entries(colors).map(n => [ RegExp(n[0], 'i'), n[1] ]));
- RegExp(n[0], 'i')
+ n[0].toLowerCase()
- m[0].test(n.innerText)
+ n.innerText.toLowerCase().includes(m[0])
const newData = data.reduce((acc, n) => {
const k = Object.keys(n)[0];
(acc.result[acc.keys[k] = (acc.keys[k] ?? -1) + 1] ??= []).push(n);
return acc;
}, { result: [], keys: {} }).result.flat();
const numKeys = new Set(data.flatMap(Object.keys)).size;
const numObjs = data.length / numKeys;
const newData = data.map((n, i, a) => a[(i % numKeys) * numObjs + (i / numKeys | 0)]);
const selector = 'селектор элементов';
const className = 'класс';
const minChildrenCount = 666;
for (const n of document.querySelectorAll(selector)) {
n.classList.toggle(className, n.children.length >= minChildrenCount);
}
// или (нет, так делать точно не надо - для 0 результат будет некорректным)
document
.querySelectorAll(`${selector} > :nth-child(${minChildrenCount})`)
.forEach(n => n.parentNode.classList.add(className));
(function toArrays(obj) {
const arr = Object.values(obj ?? {});
arr.forEach(n => n.children = toArrays(n.children));
return arr;
})(arr.reduce((acc, n) => {
const path = n.path.replace(/^\/|\/$/g, '').split('/');
const obj = path.reduce((p, c) => ((p.children ??= {})[c] ??= {}), acc);
Object.assign(obj, n);
return acc;
}, {}).children)
<div class="mainMenu">
<button data-scroll-to="calendar">Раз</button>
<button data-scroll-to="rooms">Два</button>
<button data-scroll-to="maps">Три</button>
<button data-scroll-to="contact">Четыре</button>
</div>
...
<div data-block="calendar">...</div>
<div data-block="rooms">...</div>
<div data-block="maps">...</div>
<div data-block="contact">...</div>
function scrollTo(block) {
document.querySelector(`[data-block="${block}"]`).scrollIntoView({
block: 'center',
behavior: 'smooth',
});
}
document.querySelector('.mainMenu').addEventListener('click', e => {
const block = e.target.dataset.scrollTo;
if (block) {
scrollTo(block);
}
});
// или
document.querySelectorAll('[data-scroll-to]').forEach(function(n) {
n.addEventListener('click', this);
}, e => scrollTo(e.target.dataset.scrollTo));
const names = new Set(objects.map(n => n.name));
strings.forEach(n => (names.has(n) || objects.push({ name: n })));
new Set(strings).forEach(function(n) {
if (!this.has(n)) {
objects.push({ name: n });
}
}, new Set(objects.map(n => n.name)));
// или
for (const name of strings) {
if (objects.every(n => n.name !== name)) {
objects[objects.length] = { name };
}
}
// или
objects.splice(0, objects.length, ...strings.reduce(
(acc, n) => acc.set(n, acc.get(n) ?? { name: n }),
new Map(objects.map(n => [ n.name, n ]))
).values());