const punct = '.,!?;:"\'”“';
const numStrWithPunctEnd = 3;
const arr = str.split('\n');
const index = arr.findIndex(function(n, i, a) {
return this.every(m => punct.includes(a[i + m]?.slice(-1)));
}, [...Array(numStrWithPunctEnd).keys()]);
const result = index !== -1 ? arr.slice(index).join('\n') : str;
const obj = {
a: 69,
b: 187,
c: 666,
};
const proxy = new Proxy(obj, {
set(target, key, val) {
console.log(`${key} changed from ${target[key]} to ${val}`);
target[key] = val;
return true;
},
});
function getDates(startStr, count) {
const dates = [];
const date = new Date(startStr.split('.').reverse().join('-'));
const day = date.getDate();
date.setDate(0);
while (dates.length < count) {
date.setMonth(date.getMonth() + 2, 0);
date.setDate(Math.min(date.getDate(), day));
dates.push(date.toLocaleDateString('ru-RU', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
}));
}
return dates;
}
const lines = data.split('\n').map(n => n.replace(/X\S+/, 'hello, world!!'));
document.body.addEventListener('click', e => {
document.querySelectorAll('details[open]').forEach(n => {
n.open = n === e.target.parentNode;
});
});
function createTree({
data,
idKey = 'id',
parentKey = 'parentId',
childrenKey = 'children',
}) {
const tree = Object.fromEntries(data.map(n => [ n[idKey], { ...n, [childrenKey]: [] } ]));
return Object.values(tree).filter(n => !tree[n[parentKey]]?.[childrenKey].push(n));
}
const result = createTree({
data: components,
childrenKey: 'components',
});
что делаю не так?
active
на кнопке? Его у элемента с классом d-n
переключать надо - вместо той ерунды с изменением стилей напрямую. Кстати, а кому вы пытаетесь назначить style.display = 'table-cell'
? Если идти от кнопки parent-parent-next (вместо того, чтобы несколько раз дёргать parentNode, следует использовать метод closest) - это будет (не будет, погуглите, в чём разница между nextSibling
и nextElementSibling
) строка, а не ячейка - так что перенесите-ка класс d-n
на один уровень выше. Зачем создавать каждой кнопке индивидуальный обработчик? Достаточно одного на всех, создавайте его вне цикла. Наконец, у classList.toggle
есть второй параметр, не надо им пренебрегать.document.querySelectorAll('.panel').forEach(n => n.addEventListener('click', onClick));
function onClick() {
const panel = this.closest('tr').nextElementSibling;
const isActive = !panel.classList.contains('active');
panel.classList.toggle('active', isActive);
this.classList.toggle('changing-icon', isActive);
}
мне нужен не сам ответ
function findOutlier(integers) {
const [ p0, p1, p2 ] = integers.slice(0, 3).map(n => n & 1);
return p0 === p1
? integers.find(n => (n & 1) !== p0)
: integers[+(p0 === p2)];
}
const findOutlier = arr => arr
.reduce((acc, n) => (acc[n & 1].push(n), acc), [ [], [] ])
.find(n => n.length === 1)
.pop();
const findOutlier = arr => arr
.sort((a, b) => (a & 1) - (b & 1))
.at(-((arr[0] & 1) === (arr[1] & 1)));
const filterByCount = (arr, key, f) =>
arr.filter(function(n) {
return f(this.get(n[key]));
}, arr.reduce((acc, n) => acc.set(n[key], -~acc.get(n[key])), new Map));
const newArr = filterByCount(arr, 'props1', count => count > 1);
for(var i = 0; i < tabss.children.length;i++); { tabss.children[i].classList.add('active') }
i
имеет значение tabss.children.length
, элемента с таким индексом в tabss.children
нет, ну и... ошибку вы видели. const createTreeFromNestedSets = arr => [...arr]
.sort((a, b) => a.left - b.left)
.reduce((acc, n) => {
while (acc.at(-1).at(-1).right < n.left) {
acc.pop();
}
if (acc.at(-1).at(-1).right > n.left) {
acc.push(acc.at(-1).at(-1).children);
}
acc.at(-1).push({ ...n, children: [] });
return acc;
}, [ [ { left: -Infinity, right: Infinity, children: [] } ] ])
[0][0].children;
const createTreeHTML = (arr, nodeTemplate) =>
Array.isArray(arr) && arr.length
? `<ul>${arr.map(n => `
<li>
${nodeTemplate(n)}
${createTreeHTML(n.children, nodeTemplate)}
</li>`).join('')}
</ul>`
: '';
containerElement.insertAdjacentHTML('beforeend', createTreeHTML(
createTreeFromNestedSets(data),
item => `<input data-id="${item.id}" type="checkbox">${item.name}`
));
function getDates(startStr, endStr) {
const startDate = new Date(startStr.split('.').reverse().join('-'));
const endDate = new Date(endStr.split('.').reverse().join('-'));
const dates = [];
for (; startDate <= endDate; startDate.setDate(startDate.getDate() + 1)) {
dates.push(startDate.toLocaleDateString('ru-RU', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
}));
}
return dates;
}
const inputs = [...document.querySelectorAll('.input')];
inputs.forEach(n => n.addEventListener('input', onInput));
function onInput({ target: t }) {
if (t.value.length === t.maxLength) {
t.nextElementSibling?.focus();
}
if (inputs.every(n => n.value.length === n.maxLength)) {
// здесь дёргаете свою функцию
}
}
const blockSelector = '.block';
const buttonSelector = `${blockSelector} .block__close`;
document.addEventListener('click', e => {
const block = e.target.closest(buttonSelector)?.closest(blockSelector);
block?.parentNode.removeChild(block);
});
document.querySelectorAll(buttonSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => e.currentTarget.closest(blockSelector).remove());