str.slice(1, -1).split(', ')
JSON.parse(str.replace(/[а-яё]+/g, '"$&"'))
str.match(/[^\s\[\],]+/g) ?? []
coord.split(', ').map(Number)
coord.match(/[\d.]+/g).map(n => +n)
eval(`[${coord}]`)
$('.item').on('mouseover', '.dot', function({ delegateTarget: t }) {
$('.thumb-target', t).attr('src', this.dataset.img);
$('.dot', t).removeClass('select').filter(this).addClass('select');
});
document.querySelectorAll('.item').forEach(n => {
n.addEventListener('mouseover', onMouseOver);
});
function onMouseOver({ target: t, currentTarget: ct }) {
const dot = t.closest('.dot');
if (dot) {
ct.querySelector('.thumb-target').src = dot.dataset.img;
ct.querySelectorAll('.dot').forEach(n => {
n.classList.toggle('select', n === dot);
});
}
}
const sum = (...arr) => arr
.flatMap(Object.entries)
.reduce((acc, [ k, v ]) => (
acc[k] = (acc[k] ?? 0) + v,
acc
), {});
function sum() {
const result = {};
for (const n of arguments) {
for (const k in n) {
if (n.hasOwnProperty(k)) {
if (!result.hasOwnProperty(k)) {
result[k] = 0;
}
result[k] += n[k];
}
}
}
return result;
}
const obj = sum(obj1, obj2);
. document.querySelector('#element').addEventListener('click', e => {
if (e.target.classList.contains('someclass')) {
e.preventDefault();
console.log(e.target.closest('li').dataset.id);
}
});
function onClick(e) {
e.preventDefault();
console.log(e.target.closest('li').dataset.id);
}
document.querySelectorAll('#element .someclass').forEach(n => {
n.addEventListener('click', onClick);
});
function sort(arr) {
const obj = Object.fromEntries(arr.map(n => [ n.parent, n ]));
const sorted = [];
for (let item = obj['null']; item; item = obj[item.id]) {
sorted.push(item);
}
return sorted;
}
function sort(arr, parent = null) {
const item = arr.find(n => n.parent === parent);
return item
? [ item, ...sort(arr, item.id) ]
: [];
}
const newStr = new Date(str.split(' GMT', 1)[0])
.toLocaleDateString('ru-RU')
.split('.')
.reverse()
.join(', ');
const formatDateStr = function(str) {
const [ , month, day, year ] = str.match(/(\S+) (\d+) (\d+)/);
return [ year, this[month], day.padStart(2, 0) ].join(', ');
}.bind(Object.fromEntries(Array.from({ length: 12 }, (_, i) => [
new Date(0, i).toLocaleString('en', { month: 'short' }),
`${i + 1}`.padStart(2, 0)
])));
const newStr = formatDateStr(str);
const columns = [ '#', ...new Set(persons.flatMap(Object.keys)) ];
document.body.insertAdjacentHTML('beforeend', `
<table>
<thead>
<tr>${columns.map(col => `
<th>${col}</th>`).join('')}
</tr>
</thead>
<tbody>${persons.map((person, i) => `
<tr>${columns.map((col, j) => `
<td>${j ? person[col] ?? '-' : i}</td>`).join('')}
</tr>`).join('')}
</tbody>
</table>
`);
const table = document.createElement('table');
table.createTHead().insertRow().append(...columns.map(col => {
const th = document.createElement('th');
th.textContent = col;
return th;
}));
persons.forEach(function(person, i) {
const tr = this.insertRow();
columns.forEach((col, j) => tr.insertCell().textContent = j ? person[col] ?? '-' : i);
}, table.createTBody());
document.body.append(table);
const find = (data, key) => Object
.entries(data instanceof Object ? data : {})
.reduce((found, [ k, v ]) => found ?? (k === key ? v : find(v, key)), null);
function find(data, key) {
for (const stack = [ data ]; stack.length;) {
const n = stack.pop();
if (n?.hasOwnProperty(key)) {
return n[key];
}
stack.push(...Object.values(n ?? {}));
}
return null;
}
Object.values(orders.reduce((acc, n) => {
const date = n.date.split(' ')[0];
((acc[date] ??= {
date,
documents: {},
}).documents[n.docTypesName] ??= {
date: n.date,
docId: n.docId,
docTypesName: n.docTypesName,
products: [],
}).products.push({
name: n.name,
price: n.price,
image: n.image,
qunatity: n.quantity,
});
return acc;
}, {})).map(n => (n.documents = Object.values(n.documents), n))
async function test() {
let result = null;
do {
result = await camel() || await new Promise(r => setTimeout(r, 1000));
} while (!result);
return result;
}
const flatten = arr => [].concat(...arr.map(n => Array.isArray(n) ? flatten(n) : n));
// или
function flatten(arr) {
const result = [];
for (const n of arr) {
if (n?.constructor === Array) {
[].push.apply(result, flatten(n));
} else {
result.push(n);
}
}
return result;
}
function flatten(arr) {
const result = [];
const stack = [];
for (let i = 0; i < arr.length || stack.length; i++) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else if (arr[i] instanceof Array) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, arr[i] ];
} else {
result.push(arr[i]);
}
}
return result;
}
// или
function flatten([...arr]) {
for (let i = 0; i < arr.length; i++) {
const n = arr[i];
if (n?.[Symbol.iterator] && typeof n !== 'string') {
arr.splice(i--, 1, ...n);
}
}
return arr;
}
words.some(n => str.includes(n))
const openSelector = '.block__item';
const closeSelector = '.close';
const itemSelector = '.popup';
const activeClass = 'popup--active';
// делегирование, общий обработчик клика - для открытия и закрытия сразу,
// назначается один раз для всех элементов;
// связь кнопок открытия попапов с попапами через data-атрибут
document.addEventListener('click', ({ target: t }) => {
let item = t.closest(closeSelector)?.closest(itemSelector);
if (!item) {
const open = t.closest(openSelector);
if (open) {
item = document.querySelector(`${itemSelector}.${open.dataset.popup}`);
}
}
item?.classList.toggle(activeClass);
});
// или, отдельные обработчики клика для открытия и закрытия,
// назначаются каждому элементу индивидуально;
// связь кнопок открытия попапов с попапами через индексы
const open = [...document.querySelectorAll(openSelector)];
const close = document.querySelectorAll(closeSelector);
const items = document.querySelectorAll(itemSelector);
const onOpenClick = e => items[open.indexOf(e.currentTarget)].classList.add(activeClass);
open.forEach(n => n.addEventListener('click', onOpenClick));
const onCloseClick = e => e.currentTarget.closest(itemSelector).classList.remove(activeClass);
close.forEach(n => n.addEventListener('click', onCloseClick));