new MutationObserver((mutations, observer) => {
if (mutations[0].target.classList.contains('интересующий-вас-класс')) {
observer.disconnect();
typed.start();
}
}).observe(элементНаличиеКлассаУКоторогоНадоОтследить, { attributes: true });
const getTheNearestLocation = (locations, [ x, y ]) =>
locations.reduce((nearest, n) => {
const d = ((n[1][0] - x) ** 2 + (n[1][1] - y) ** 2) ** 0.5;
return nearest[1] < d ? nearest : [ n, d ];
}, [ null, Infinity ])[0];
const parent = document.querySelector('ul');
const id = 'item';
const elems = Array.from(parent.children);
const index = elems.findIndex(n => n.id === id);
const result = index === -1 ? elems : elems.slice(0, index);
// или
const result = [...parent.querySelectorAll(`:not(#${id}, #${id} ~ *)`)];
// или
const result = [];
for (
let el = parent.firstElementChild;
el && el.id !== id;
el = el.nextElementSibling
) {
result.push(el);
}
const result = arr
.map(Object.values)
.sort((a, b) => b - a)
.slice(0, 3)
.join(', ');
map
следовало бы использовать flatMap
, но пока в элементах массива содержится по одному свойству - и так сойдёт. const makeCensored = (str, words, replacement = '***') =>
str
.split(' ')
.map(n => words.includes(n) ? replacement : n)
.join(' ');
const group = (arr, idKey, valKey) =>
Object.values(arr.reduce((acc, { [idKey]: id, [valKey]: val }) => (
(acc[id] ??= { [idKey]: id, [valKey]: [] })[valKey].push(val),
acc
), {}));
const result = group(data, 'id', 'color');
function group(data, key, val = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const getVal = val instanceof Function ? val : n => n[val];
const result = new Map;
for (const n of data) {
const k = getKey(n);
result.set(k, result.get(k) ?? []).get(k).push(getVal(n));
}
return result;
}
const result = Array.from(
group(data, 'id', 'color'),
([ id, colors ]) => ({ id, colors })
);
str.split(';').pop()
// или
str.replace(/.*;/, '')
// или
str.match(/;(.*)/)[1]
// или
/[^;]+$/.exec(str).shift()
// или
str.slice(str.lastIndexOf(';') + 1)
// или
[...str].reduce((acc, n) => n === ';' ? '' : acc + n)
// или
Array.from(str).filter((n, i, a) => !a.includes(';', i)).join('')
const newArr = arr.map(function(n) {
return [ ...n, ...Array(this - n.length).fill('') ];
}, Math.max(...arr.map(n => n.length)));
const max = arr.reduce((max, { length: n }) => max > n ? max : n, 0);
arr.forEach(n => n.push(...Array(max - n.length).fill('')));
parseInt('1!!!') // 1
+'1!!!' // NaN
parseInt('') // NaN
+'' // 0
parseInt('3.14159') // 3
+'3.14159' // 3.14159
parseInt('0b1000101') // 0
+'0b1000101' // 69
parseInt('0o273') // 0
+'0o273' // 187
parseInt({ valueOf: () => 666 }) // NaN
+({ valueOf: () => 666 }) // 666
parseInt('1000000000', 2) // 512
+'1000000000' // 1000000000
parseInt('99', 8) // NaN
+'99' // 99
parseInt('DEAD', 16) // 57005
+'DEAD' // NaN
const target = document.querySelector('.color__des-item');
const container = document.querySelector('.color__list');
const key = 'name';
const attr = `data-${key}`;
const buttonSelector = `[${attr}]`;
const getAttr = el => el.dataset[key];
// или
const getAttr = el => el.getAttribute(attr);
// или
const getAttr = el => el.attributes[attr].value;
container.querySelectorAll(buttonSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => target.textContent = getAttr(e.currentTarget));
container.addEventListener('click', ({ target: t }) =>
(t = t.closest(buttonSelector)) &&
(target.innerText = getAttr(t))
);
function update(target, source, key, props) {
source.forEach(function(n) {
const item = this[n[key]];
item && props.forEach(m => item[m] = n[m]);
}, Object.fromEntries(target.map(n => [ n[key], n ])));
}
update(directions, [ { раз объект }, { два объект }, ... ], 'id', [ 'color' ]);
document.addEventListener('click', e => {
let t = e.target;
for (; t !== document && !t.matches('.more-btn'); t = t.parentNode) ;
for (const n of document.getElementsByClassName('more-btn')) {
n.classList.toggle('active', n === t && !n.classList.contains('active'));
}
// или
document.querySelectorAll('.more-btn').forEach(function(n) {
n.classList[n === this ? 'toggle' : 'remove']('active');
}, e.target.closest('.more-btn'));
});
function weightedRandom(arr, key = () => 1) {
const val = key instanceof Function ? key : n => n[key];
const max = arr.reduce((acc, n) => acc + val(n), 0);
return () => {
let rand = Math.random() * max;
return arr.find(n => (rand -= val(n)) < 0);
};
}
const getRandomPhotosArray = weightedRandom([
[ 9, truePhotos ],
[ 1, funnyPhotos ],
], 0);
function getPhoto() {
const photos = getRandomPhotosArray()[1];
return photos[Math.random() * photos.length | 0];
}
new ApexCharts(..., {
...
tooltip: {
...
y: {
title: {
formatter: (seriesName, seriesData) => ...,
},
formatter: (value, seriesData) => ...,
},
},
});
const getFromTree = (tree, childrenKey, getter = n => n) =>
Array.isArray(tree)
? tree.flatMap(n => [
getter(n),
...getFromTree(n[childrenKey], childrenKey, getter),
])
: [];
// или
function* flatTree(tree, childrenKey) {
if (
tree instanceof Object &&
tree[Symbol.iterator] instanceof Function
) {
for (const n of tree) {
yield n;
yield* getFromTree(n[childrenKey], childrenKey);
}
}
}
const getFromTree = function(tree, childrenKey, getter = n => n) {
const result = [];
for (const stack = this(tree); stack.length;) {
const n = stack.pop();
result.push(getter(n));
stack.push(...this(n[childrenKey]));
}
return result;
}.bind(x => x instanceof Array ? [...x].reverse() : []);
// или
const flatTree = function*(tree, childrenKey) {
const stack = [];
for (let [ i, arr ] = this(tree); ++i < arr.length || stack.length;) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else {
yield arr[i];
stack.push([ i, arr ]);
[ i, arr ] = this(arr[i][childrenKey]);
}
}
}.bind(x => [ -1, x?.constructor === Array ? x : [] ]);
getFromTree(tree, 'children').forEach(n => console.log(n));
// или
for (const n of flatTree(tree, 'children')) {
console.log(n);
}
function createTree({
data,
key = 'id',
parentKey = 'parentId',
childrenKey = 'children',
}) {
const tree = Object.fromEntries(data.map(n => [ n[key], { ...n } ]));
return Object.fromEntries(Object.entries(tree).filter(([ , n ]) => !(
tree[n[parentKey]] && ((tree[n[parentKey]][childrenKey] ??= {})[n[key]] = n)
)));
}
const tree = createTree({
data: arr,
key: 'uid',
parentKey: 'parentUID',
});
menu.insertAdjacentHTML('beforeend', arr
.map(n => `<li>${n}</li>`)
.join('')
);
// или
menu.append(...arr.reduce((acc, n) => (
(acc[acc.length] = document.createElement('li')).textContent = n,
acc
), []));
// или
for (const n of arr) {
menu.appendChild(document.createElement('li'));
menu.lastChild.innerText = n;
}
// или
arr.forEach(n => {
const li = document.createElement('li');
li.insertBefore(new Text(n), null);
menu.insertBefore(li, null);
});
// или
(function add(i) {
if (i < arr.length) {
menu.insertAdjacentElement('beforeend', document.createElement('li'));
menu.children[~-menu.children.length].innerHTML = arr[i];
add(-~i);
}
})(0);