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
), {})
const names = [ 'иван', 'антон' ] as const;
type Name = typeof names[number];
const fn = (name: Name) => name;
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);
}
const [ coord, setCoord ] = useState(...);
function onActionTickComplete(e) {
const projection = e.get('target').options.get('projection');
const { globalPixelCenter, zoom } = e.get('tick');
setCoord(projection.fromGlobalPixels(globalPixelCenter, zoom));
}
<Map
onActionTickComplete={onActionTickComplete}
...
>
<Placemark geometry={coord} />
</Map>
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 toggleSearchParams = params => {
const newSearchParams = [...searchParams];
for (const n of params) {
const index = newSearchParams.findIndex(m => n[0] === m[0] && n[1] === m[1]);
if (index === -1) {
newSearchParams.push(n);
} else {
newSearchParams.splice(index, 1);
}
}
setSearchParams(newSearchParams);
};
const handleChangeCheckBoxValue = e => {
toggleSearchParams([ [ 'selected', e.target.value ] ]);
};
const handleDeleteParams = () => {
toggleSearchParams(checkboxParams.map(n => [ 'selected', n ]));
};
swiper.on('slideChange', ({ activeIndex }) => {
document.querySelectorAll('.points .point').forEach((n, i) => {
n.classList.toggle('active', i === activeIndex);
});
})
document.querySelector('.points').addEventListener('click', ({ target: t }) => {
if (t.classList.contains('point')) {
swiper.slideTo([...t.parentNode.children].indexOf(t));
}
});
pagination: {
el: '.points',
bulletClass: 'point',
bulletActiveClass: 'active',
renderBullet: (index, className) => `<div class="${className}">${index + 1}</div>`,
clickable: true,
},
const payload = {
data: Object.fromEntries([
'раз свойство',
'два свойство',
'три свойство',
].map(n => [ n, this[n] ])),
};
Удалили под индексом 2 <...> элемента под индексом 2 нет
как вернуть к первоначальному состоянию когда unchecked не понимаю
function Posts() {
const [ posts, setPosts ] = useState([]);
const [ filteredPosts, setFilteredPosts ] = useState([]);
const [ search, setSearch ] = useState('');
const [ checkbox, setCheckbox ] = useState(false);
useEffect(() => {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then(r => setPosts(r.data));
}, []);
useEffect(() => {
let filtered = posts;
if (search) {
const s = search.toLowerCase();
filtered = filtered.filter(n => n.title.toLowerCase().includes(s));
}
if (checkbox) {
filtered = filtered.filter(n => n.userId === 10);
}
setFilteredPosts(filtered);
}, [ posts, search, checkbox ]);
return (
<>
<input
type="text"
placeholder="Search for article..."
value={search}
onChange={e => setSearch(e.target.value)}
/>
<label>
User Id 10
<input
type="checkbox"
checked={checkbox}
onChange={e => setCheckbox(e.target.checked)}
/>
</label>
<ul>
{filteredPosts.map(n => (
<li key={n.id}>
<div>{n.userId}</div>
<div>{n.title}</div>
<div>{n.body}</div>
</li>
))}
</ul>
</>
);
}
new MutationObserver((mutations, observer) => {
if (mutations[0].target.classList.contains('интересующий-вас-класс')) {
observer.disconnect();
typed.start();
}
}).observe(элементНаличиеКлассаУКоторогоНадоОтследить, { attributes: true });