tags = Array.from(new Set(data.flatMap(n => n.tags)));
tags.splice(0, tags.length, ...new Set(data.flatMap(n => n.tags)));
async function getFirstLoadedImage(urls) {
for (const n of urls) {
try {
return await loadImage(n);
} catch (e) {}
}
throw 'ничего загрузить не удалось';
}
const getFirstLoadedImage = (urls, i = 0) => i < urls.length
? loadImage(urls[i]).catch(() => getFirstLoadedImage(urls, -~i))
: Promise.reject('ничего загрузить не удалось');
getFirstLoadedImage(resolutions.map(n => `https://i.ytimg.com/vi/${videoId}/${n}.jpg`))
.then(img => document.body.append(img))
.catch(console.error);
function groupValues(arr, defaultValue = null) {
const keys = [...new Set(arr.flatMap(Object.keys))];
return arr.reduce((acc, n) => {
keys.forEach(k => acc[k].push(Object.hasOwn(n, k) ? n[k] : defaultValue));
return acc;
}, Object.fromEntries(keys.map(k => [ k, [] ])));
}
const result = groupValues(arr);
const groupValues = (arr, defaultValue = null) =>
arr.reduce((acc, n, i, a) => (
Object
.keys(n)
.forEach(k => (acc[k] ??= Array(a.length).fill(defaultValue))[i] = n[k]),
acc
), {});
const containerSelector = '.selectboxss';
const itemClass = 'selectoption';
const itemSelector = `${containerSelector} .${itemClass}`;
const getClasses = el => Array.prototype.filter.call(el.classList, n => n !== itemClass);
//const getClass = el => el.className.match(RegExp(`${itemClass}-\\d+`))[0];
function updateClasses(item) {
const container = item.closest(containerSelector);
const { classList: cl } = container;
cl.remove(...Array.prototype.flatMap.call(container.querySelectorAll(itemSelector), getClasses));
cl.add(...getClasses(item));
//cl.remove(...Array.from(container.querySelectorAll(itemSelector), getClass));
//cl.add(getClass(li));
}
document.querySelectorAll(itemSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => updateClasses(e.currentTarget));
document.addEventListener('click', e => {
const item = e.target.closest(itemSelector);
if (item) {
updateClasses(item);
}
});
tableValues(element);
element.children
/element.childNodes
.document.querySelector('form').childNodes
children
вместо childNodes
. Ну и погуглите, в чём между ними разница.if (element.nodeType == 1 && element.nodeName == 'INPUT' || element.nodeName == 'SELECT') {
nodeType
лишняя. Кроме того, вам не помешает разобраться с приоритетом выполнения операторов - nodeType
вы тут проверяете только для input'а.let result = [];
const getValues = el =>
el instanceof Element
? [ 'INPUT', 'SELECT' ].includes(el.tagName)
? [ el.value ]
: [...el.children].flatMap(getValues)
: [];
// или
const getValues = el =>
[ 'INPUT', 'SELECT' ].includes(el?.tagName)
? [ el.value ]
: [].flatMap.call(el.children ?? [], getValues);
const values = getValues(document.querySelector('form'));
const values = Array.from(document.querySelector('form').elements, n => n.value);
const getFromDOMNodes = (node, test, getVal) =>
node instanceof Node
? Array.prototype.reduce.call(
node.childNodes,
(acc, n) => (acc.push(...getFromDOMNodes(n, test, getVal)), acc),
test(node) ? [ getVal(node) ] : []
)
: [];
const values = getFromDOMNodes(
document.querySelector('form'),
node => [ 'INPUT', 'SELECT' ].includes(node.nodeName),
node => node.value
);
const values = {
RUS: [ 'раз значение', 'два значение', 'три' ],
US: [ '...', '...', '...' ],
// ...
};
const items = document.querySelectorAll('li');
const buttons = document.querySelectorAll('button');
buttons.forEach(n => n.addEventListener('click', onClick));
function onClick({ target: { innerText: key } }) {
items.forEach(function(n, i) {
n.innerText = this[i] ?? `ЗНАЧЕНИЕ #${i} ДЛЯ ${key} НЕ ЗАДАНО`;
}, values[key] ?? []);
}
const buttonSelector = '.added';
const itemSelector = '.added-block';
const activeClass = '_active';
const notActiveSelector = `${itemSelector}:not(.${activeClass})`;
const newActiveCount = 2;
function onButtonClick(button) {
const items = [...button.parentNode.querySelectorAll(notActiveSelector)];
items.slice(0, newActiveCount).forEach(n => n.classList.add(activeClass));
button.disabled = items.length <= newActiveCount;
}
document.querySelectorAll(buttonSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => onButtonClick(e.currentTarget));
document.addEventListener('click', e => {
const button = e.target.closest(buttonSelector);
if (button) {
onButtonClick(button);
}
});
str.match(/\d+/g).join('.')
/[^\/]+(?=\/$)/.exec(str)[0]
str.match(/[^\/]+/g).pop()
str.split('/').at(-2)
Хук get не позволяет получить параметры вызова метода
function sequence(functions) {
return new Proxy(functions, {
get(target, key) {
const val = target[key];
return val instanceof Function
? (...args) => {
console.log(`${key} called with arguments: `, args);
return val.apply(target, args);
}
: val;
},
});
}
const uniqueWithSum = arr =>
arr.reduce((acc, n) => {
const keys = n.slice(0, -1);
const item = acc.find(m => m.length === n.length && keys.every((k, i) => k === m[i]));
(item ?? (acc[acc.length] = [ ...keys, 0 ]))[keys.length] += n[keys.length];
return acc;
}, []);
const uniqueWithSum = (function(arr) {
const indexTree = new Map;
return arr.reduce((acc, [...keys]) => {
const val = keys.pop();
const indexes = keys.reduce((p, c) => p.set(c, p.get(c) ?? new Map).get(c), indexTree);
const index = indexes.set(this, indexes.get(this) ?? ~-acc.push([ ...keys, 0 ])).get(this);
acc[index][keys.length] += val;
return acc;
}, []);
}).bind(Symbol());
const uniqueWithSum = arr =>
[...arr.reduce((acc, n) => {
const end = n.length - 1;
const key = n.reduce((p, c, i) => i === end ? p : p.set(c, p.get(c) ?? new Map).get(c), acc[0]);
acc[1].set(key, acc[1].get(key) ?? n.map((m, i) => i !== end && m)).get(key)[end] += n[end];
return acc;
}, [ new Map, new Map ])[1].values()];
const replaceKeys = (value, replacer) =>
value instanceof Object
? value instanceof Array
? value.map(n => replaceKeys(n, replacer))
: Object.fromEntries(Object
.entries(value)
.map(n => [ replacer(n[0]), replaceKeys(n[1], replacer) ])
)
: value;
const newObj = replaceKeys(obj, k => `${k}_upd`);
function replaceKeys(value, replacer) {
const stack = [];
const clones = new Map;
const getClone = val => val instanceof Object
? (clones.has(val) || stack.push([ val, clones.set(val, val.constructor()).get(val) ]),
clones.get(val))
: val;
for (getClone(value); stack.length;) {
const [ source, target ] = stack.pop();
const isArray = Array.isArray(source);
for (const k in source) if (Object.hasOwn(source, k)) {
target[isArray ? k : replacer(k)] = getClone(source[k]);
}
}
return getClone(value);
}
const regex = /#[a-f\d]+;$/i;
const replacement = '<span class="color" style="background: $&"></span>';
document.querySelectorAll('селектор сами сообразите').forEach(n => {
n.innerHTML = n.innerText.replace(regex, replacement);
});
const result = arr.reduce((acc, n, i, a) => (
n === a[i - 1] + 1 || acc.push([]),
acc.at(-1).push(n),
acc
), []);
function groupAdjacent(
data,
{
key = n => n,
newGroup = (c, p) => c !== p,
} = {}
) {
const result = [];
const getVal = key instanceof Function ? key : n => n[key];
let prev = null;
let i = -1;
for (const n of data) {
const curr = getVal(n, ++i);
if (!result.length || newGroup(curr, prev)) {
result.push([]);
}
result.at(-1).push(n);
prev = curr;
}
return result;
}
const result = groupAdjacent(arr, { newGroup: (c, p) => c !== -~p });
// или
const result = groupAdjacent(arr, { key: (n, i) => n - i });
.product
. Вместо первого .product
нужен тот, внутри которого находится нажатая кнопка:document.querySelector('.wrapper_product')
---> event.target
menu.addEventListener('click', ({ target: t }) => {
if (t.tagName === 'SPAN') {
const parent = t.parentNode;
parent.classList.toggle('active');
for (const n of menu.querySelectorAll('.active')) {
if (n !== parent) {
n.classList.toggle('active', n.contains(parent));
}
}
}
});
- .menu_list_item.active .submenu {
+ .active > .submenu {
- .submenu_list_item.active .product {
+ .active > .product {
const container = document.querySelector('#menu');
const itemSelector = 'li';
const buttonSelector = `${itemSelector} span`;
const activeClass = 'active';
container.addEventListener('click', function(e) {
const item = e.target.closest(buttonSelector)?.closest(itemSelector);
if (item) {
item.classList.toggle(activeClass);
this.querySelectorAll(`.${activeClass}`).forEach(n => {
if (n !== item) {
n.classList.toggle(activeClass, n.contains(item));
}
});
}
});