const countUniqueChars = str =>
new Set(str).size;const countUniqueChars = str => [...str]
.reduce((acc, n) => (acc.includes(n) || acc.push(n), acc), [])
.length;const countUniqueChars = str => Array
.from(str)
.reduce((acc, n, i, a) => acc + (i === a.indexOf(n)), 0);const countUniqueChars = str => Object
.keys(Object.fromEntries([].map.call(str, n => [ n, 1 ])))
.length;const countUniqueChars = str => str
.split('')
.sort()
.filter((n, i, a) => n !== a[i - 1])
.length;const countUniqueChars = str =>
(str && str.match(/(.)(?!.*\1)/g)).length;
<div class="xxx">hello, world!!</div>
<div class="xxx">fuck the world</div>
<div class="xxx">fuck everything</div>.xxx {
padding: 10px;
margin: 10px;
border: 1px solid silver;
}let el = null;
document.addEventListener('mousedown', e => el = e.target.closest('.xxx'));
document.addEventListener('mouseup', e => el = null);
document.addEventListener('mousemove', e => {
if (el) {
const height = parseInt(getComputedStyle(el).height);
el.style.height = `${height + e.movementY}px`;
}
});
const { id } = Object.values(CategoryProduct).flat().find(n => n.name === name) || {};
const selector = 'li.my_class a[href="#"]';.document.querySelectorAll(selector).forEach(function(n) {
n.addEventListener('click', this);
}, e => e.preventDefault());document.addEventListener('click', e => {
const link = e.target.closest(selector);
if (link) {
e.preventDefault();
}
});
Не могу понять, что в моём коде не так.
function getIndexOfWarmestDay(data){let max = 0;resultArr += max;max = 0;console.log(resultArr);console.log тут надо делать return.data.map(n => Math.max(...n)).
function scrollTracking() {
const wt = $(window).scrollTop();
const wh = $(window).height();
$('#console').html($('.active').get().find(n => {
const et = $(n).offset().top;
const eh = $(n).outerHeight();
return wt > et && wt + wh - eh * 2 <= et + (wh - eh);
}) ? 'Работает' : 'Не работает');
}
[ 1, 2 ], например. Или [ 5, 6, 8, 9 ].const range = ([...arr]) => arr
.sort((a, b) => a - b)
.reduce((acc, n, i, a) => (
(n === a[i - 1] + 1) || acc.push([ n ]),
acc[acc.length - 1][1] = n,
acc
), [])
.map(([ a, b ]) => a === b ? a : `${a}-${b}`)
.join(', ');const range = arr => ''.concat(...arr
.slice()
.sort((a, b) => a - b)
.reduce((acc, n, i, a) => (
n !== a[i - 1] + 1 && acc.push(i ? `, ${n}` : n),
n === a[i - 1] + 1 && n !== a[i + 1] - 1 && acc.push(`-${n}`),
acc
), [])
);
function interval(arr, delay, callback) {
let i = ~-arr.length;
return arr.length
? setInterval(() => callback(arr[i], arr[i = -~i % arr.length]), delay)
: null;
}
// или
function interval(arr, delay, callback) {
let timeoutId = null;
arr.length && (function step(i) {
timeoutId = setTimeout(() => {
callback(arr[i++], arr[i %= arr.length]);
step(i);
}, delay);
})(arr.length - 1);
return () => clearTimeout(timeoutId);
}interval(
document.querySelectorAll('.banner-block'),
300,
(prev, curr) => {
prev.classList.remove('active');
curr.classList.add('active');
}
);interval, для первой версии передавать этот результат в clearInterval, а для второй вызвать его.
$('.num').each(function() {
$({ value: 0 }).animate({ value: +$(this).text() }, {
duration: 1000,
easing: 'linear',
step: val => $(this).text(val.toFixed(2)),
});
});
.item добавить data-атрибуты, указывающие, выбор какого типа осуществляется с помощью кнопок внутри (only - выбран может быть только один вариант вообще, one - выбран может быть только один вариант внутри данного .item, multiple - можно выбирать произвольное количество вариантов внутри данного .item):<div class="item" data-type="only">
<h2>Выбрать все категории</h2>
...
</div>
<div class="item" data-type="one">
<h2>Выбрать пол</h2>
...
</div>
<div class="item" data-type="multiple">
<h2>Выбрать тип одежды</h2>
...
</div>const containerSelector = '.filter';
const itemSelector = `${containerSelector} .item`;
const baseBtnSelector = 'button';
const btnSelector = `${itemSelector} ${baseBtnSelector}`;
const btnOnlySelector = `${itemSelector}[data-type="only"] ${baseBtnSelector}`;
const activeClass = 'active';
document.addEventListener('click', ({ target: t }) => {
const button = t.closest(btnSelector);
if (button) {
const toggle = n => n.classList.toggle(activeClass, n === button);
const item = button.closest(itemSelector);
const { type } = item.dataset;
item
.closest(containerSelector)
.querySelectorAll(type === 'only' ? btnSelector : btnOnlySelector)
.forEach(toggle);
if (type === 'multiple') {
button.classList.toggle(activeClass);
} else if (type === 'one') {
item.querySelectorAll(btnSelector).forEach(toggle);
}
}
});
function merge(nums1, m, nums2, n) {
for (let i = m + n, i1 = m - 1, i2 = n - 1; i--;) {
nums1[i] = i2 < 0 || nums1[i1] > nums2[i2] ? nums1[i1--] : nums2[i2--];
}
}
function randomCall(items) {
const max = items.reduce((acc, n) => acc + n.ratio, 0);
return function(...args) {
const val = Math.random() * max;
for (let sum = 0, i = 0; i < items.length; i++) {
sum += items[i].ratio;
if (sum > val) {
return items[i].func.apply(this, args);
}
}
};
}const func = randomCall([
{ func: func1, ratio: 1 },
{ func: func2, ratio: 2 },
{ func: func3, ratio: 3 },
{ func: func4, ratio: 4 },
]);
const value = 'myValue';.// если речь идёт о каком-то конкретном свойстве
const hasValue = x => x && x.value === value;
// если имя свойства не важно
const hasValue = x => Object.values(x || {}).includes(value);const find = (data, test) =>
test(data)
? data
: data === Object(data)
? Object.values(data).reduce((found, n) =>
found !== null ? found : find(n, test)
, null)
: null;function find(data, test) {
for (const stack = [ data ]; stack.length;) {
const n = stack.pop();
if (test(n)) {
return n;
} else if (n instanceof Object) {
stack.push(...Object.values(n).reverse());
}
}
return null;
}const obj = find(arrayData, hasValue);.
.item, а не вложенные в него элементы:.item[data-xxx="1"]::before { background: #444; }
.item[data-xxx="2"]::before { background: #555; }
.item[data-xxx="3"]::before { background: #666; }
.item[data-xxx="4"]::before { background: #777; }
.item[data-xxx="5"]::before { background: #888; }
.item[data-xxx="6"]::before { background: #999; }.item не надо:$('#counter').on('input', e => {
$('#results').html('<div class="item"></div>'.repeat(e.target.value));
}).trigger('input');
// или
const results = document.querySelector('#results');
const counter = document.querySelector('#counter');
counter.addEventListener('input', ({ target: { value } }) => {
results.innerHTML = Array(++value).join('<div class="item"></div>');
});
counter.dispatchEvent(new Event('input'));$('#view').on('click', () => $('.item').attr('data-xxx', () => 1 + Math.random() * 6 | 0));
// или
document.querySelector('#view').addEventListener('click', () => {
document.querySelectorAll('.item').forEach(n => n.dataset.xxx = -~(Math.random() * 6));
});
document.querySelector('table').addEventListener('click', ({ target: t }) => {
const next = t.matches('input[type="button"]') && t.parentNode.nextElementSibling;
const input = next && next.querySelector('input');
input && (input.type = 'text');
});
Object.fromEntries((url.match(/(?<=utm_).+?=[^&]*/g) || []).map(n => n.split('=')))[...url.matchAll(/utm_([^=]+)=([^&]*)/g)].reduce((acc, [ , k, v ]) => (acc[k] = v, acc), {})Array
.from(new URL(url).searchParams)
.filter(n => n[0].startsWith('utm_'))
.reduce((acc, n) => ({ ...acc, [n[0].slice(4)]: n[1] }), {})
select.value = '0';select.selectedIndex = 0;true в качестве значения свойства selected тому option'у, на который хотите переключиться:select[0].selected = true;
// или
select.options[0].selected = true;
// или
select.children[0].selected = true;
// или
select.firstElementChild.selected = true;
// или
select.querySelector('[selected]').selected = true;select.innerHTML += '';
const disableByType = (elements, type) =>
elements.forEach(n => n.disabled = n.dataset.type2 !== type);// можно сделать делегированный обработчик
document.addEventListener('change', ({ target: { dataset: { type1 } } }) => {
if (type1) {
disableByType(document.querySelectorAll('[data-type2]'), type1);
}
});
// или, назначить обработчик каждой радиокнопке индивидуально
const radios1 = document.querySelectorAll('[data-type1]');
const radios2 = document.querySelectorAll('[data-type2]');
const onChange = e => disableByType(radios2, e.target.dataset.type1);
radios1.forEach(n => n.addEventListener('change', onChange));