document.querySelector('.ticket_content').addEventListener('input', e => {
document.querySelector('.ticket_price').innerText =
Array.prototype.reduce.call(
e.currentTarget.querySelectorAll('.plus_minus'),
(acc, n) => acc + n.querySelector('input').value * n.nextElementSibling.innerText,
0
);
});
document.querySelectorAll('.item').forEach((n, i) => {
n.querySelectorAll('.card-item').forEach(m => m.textContent = `button ${i}`);
});
for (const [ i, n ] of document.querySelectorAll('.item').entries()) {
for (const m of n.getElementsByClassName('card-item')) {
m.innerText = 'button ' + i;
}
}
const items = document.querySelector('.parent-list').children;
for (let i = 0; i < items.length; i++) {
const subitems = items[i].querySelector('.card-list').children;
for (let j = 0; j < subitems.length; j++) {
subitems[j].innerHTML = 'button '.concat(i);
}
}
const bullshitInsert = str => str
.replace(/(?<=[2468])(?=[2468])/g, '*')
.replace(/(?<=[13579])(?=[13579])/g, '-');
const bullshitInsert = str => Array
.from(str, (n, i) => (n * str[i - 1] && !((n ^ str[i - 1]) & 1) ? '*-'[n & 1] : '') + n)
.join('');
const result = Object
.entries(arr.reduce((acc, n) => ((acc[n.name] ??= []).push(n.value), acc), {}))
.reduce((acc, [ k, v ]) => (acc[k] = v.length === 1 || v, acc), {});
ThirdName: true
true
там, где значение одно:const result = Object
.entries(arr.reduce((acc, n) => ((acc[n.name] ??= new Set).add(n.value), acc), {}))
.reduce((acc, [ k, [...v] ]) => (acc[k] = ~-v.length ? v : v[0], acc), {});
const filter = (arr, conditions) =>
arr.filter(
function(n) {
return this.every(([ k, values ]) => values.some(v => v.includes(n[k])));
},
Object
.entries(conditions)
.map(n => [ n[0], [].concat(n[1]).map(String) ])
.filter(n => n[1].length)
);
А лучше всего просто объяснить что бы я в итоге допер сам!
const { drawImage } = canvas.getContext('2d') as CanvasRenderingContext2D; drawImage( ...
const obj = {
fucking_value: 666,
fucking_method() {
if (!this.hasOwnProperty('fucking_value')) {
throw 'FUCK OFF';
}
console.log(this.fucking_value);
},
};
const { fucking_method } = obj;
fucking_method();
this
- бегом гуглить, разбираться, что это, зачем, к каким значениям в каких случаях даёт доступ.document.querySelector('.form').addEventListener('input', e => {
const data = Array.from(
e.currentTarget.children,
n => Array.from(n.querySelectorAll('input'), m => m.value)
);
document.querySelector('.total').innerText = Array
.from(document.querySelectorAll('.row'))
.reduce((acc, n, i) => {
data[i].forEach((m, j) => n.children[j + 1].innerText = m);
return acc + (+data[i].at(-1) || 0);
}, 0);
});
const total = document.querySelector('.total');
const form = document.querySelector('.form');
const formRows = form.getElementsByClassName('d-flex');
const tableRows = document.getElementsByClassName('row');
form.addEventListener('input', ({ target: t }) => {
const inputBox = t.closest('.input-box');
const formRow = inputBox.parentNode;
const iRow = Array.prototype.indexOf.call(formRows, formRow);
const iCol = -~Array.prototype.indexOf.call(formRow.children, inputBox);
tableRows[iRow].cells[iCol].textContent = t.value;
if (iCol === formRow.children.length) {
total.textContent = Array.prototype.reduce.call(
formRows,
(acc, n) => acc + (n.lastElementChild.children[0].value | 0),
0
);
}
});
const flat = (arr, childrenKey) =>
arr instanceof Array
? arr.flatMap(({ [childrenKey]: c, ...n }) => [ n, ...flat(c, childrenKey) ])
: [];
const result = flat(items, 'children');
function flat(arr, childrenKey) {
const result = [];
for (const stack = [...arr].reverse(); stack.length;) {
const { [childrenKey]: c, ...n } = stack.pop();
if (Array.isArray(c) && c.length) {
stack.push(...[...c].reverse());
}
result.push(n);
}
return result;
}
// или
function flat(arr, childrenKey) {
const result = [];
const stack = [];
for (let i = 0; i < arr.length || stack.length; i++) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else {
const { [childrenKey]: c, ...n } = arr[i];
if (c?.constructor === Array && c.length) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, c ];
}
result.push(n);
}
}
return result;
}
// или
function flat([...arr], childrenKey) {
for (const [ i, { [childrenKey]: c, ...n } ] of arr.entries()) {
arr.splice(i, 1, n, ...(c?.[Symbol.iterator] && typeof c !== 'string' ? c : []));
}
return arr;
}
const obj = new Proxy({}, {
get(target, key) {
const lowerKey = key.toLowerCase();
return target[Object.hasOwn(target, lowerKey) ? lowerKey : key];
},
set(target, key, val) {
target[key.toLowerCase()] = val;
return true;
},
has(target, key) {
return key in target || key.toLowerCase() in target;
},
defineProperty(target, key, descriptor) {
return Object.defineProperty(target, key.toLowerCase(), descriptor);
},
deleteProperty(target, key) {
return delete target[key.toLowerCase()];
},
getOwnPropertyDescriptor(target, key) {
return Object.getOwnPropertyDescriptor(target, key.toLowerCase());
},
});
const merge = (key, ...arrs) =>
Object.values(arrs.reduce((acc, arr) => (
arr.forEach(n => Object.assign(acc[n[key]] ??= {}, n)),
acc
), {}));
const result = merge('id', sum, arr1, arr2);
const merge = (key, ...arrs) =>
Array.from(arrs
.flat()
.reduce((acc, n) => {
const k = key(n);
return acc.set(k, Object.assign(acc.get(k) ?? {}, n));
}, new Map)
.values()
);
const result = merge(n => n.id, sum, arr1, arr2);
const result = arr.map(function(n) {
return this[n];
}, Object.fromEntries(sum.map(n => [ n.id, n.name ])));
// или
const names = new Map(sum.map(n => [ n.id, n.name ]));
const result = arr.map(n => names.get(n));
// или
const result = arr.map(n => sum.find(m => m.id === n)?.name);
sum
отсутствуют некоторые из нужных элементов, а получать undefined
внутри массива с результатами не хочется?const result = arr.map(function(n) {
return this[n] ?? 'объекта с таким id нет';
}, Object.fromEntries(sum.map(n => [ n.id, n.name ])));
const names = new Map(sum.map(n => [ n.id, n.name ]));
const result = arr.reduce((acc, n) => (names.has(n) && acc.push(names.get(n)), acc), []);
document.querySelectorAll('.parent').forEach((n, i) => {
n.insertAdjacentHTML('beforeend', `<div class="child">${arr[i]}</div>`);
});
for (const [ i, n ] of document.querySelectorAll('.parent').entries()) {
const div = document.createElement('div');
div.className = 'child';
div.textContent = arr[i];
n.append(div);
}
$('.parent').append(i => `<div class="child">${arr[i]}</div>`);
const createArr = length =>
Array.from({ length }, (_, i) =>
Array.from({ length }, (_, j) =>
(i === j || i === length - j - 1) +
((i <= j && i <= length - j - 1) || (i >= j && i >= length - j - 1))
)
);
const newArr = arr.reduce((acc, n) => (
acc.push({ ...n, fractionTotal: n.fraction + (acc.at(-1)?.fractionTotal ?? 0) }),
acc
), []);
// или
const newArr = arr.map(function({ ...n }) {
n.fractionTotal = this[0] += n.fraction;
return n;
}, [ 0 ]);
arr.forEach((n, i, a) => n.fractionTotal = n.fraction + (i && a[i - 1].fractionTotal));
// или
arr.reduce((acc, n) => n.fractionTotal = acc + n.fraction, 0);
const rows = 8;
const cols = 8;
document.body.innerHTML = Array
.from({ length: rows }, (_, i) => Array
.from({ length: cols }, (_, j) => (i ^ j) & 1)
.join(''))
.join('<br>');
const sorted = (data, keys) => Array
.from(data, n => [ n ].concat(keys(n)))
.sort((a, b) => {
let diff = 0;
for (let i = 0; ++i < a.length && !(diff = ((a[i] < b[i]) ? -1 : +(a[i] > b[i])));) ;
return diff;
})
.map(n => n[0]);
const sortChildren = (el, keys) =>
el.append(...sorted(el.children, keys));
const ul = document.querySelector('ul');
ul.addEventListener('change', e => sortChildren(
e.currentTarget,
el => [
-el.querySelector('input').checked,
el.innerText.trim().toLowerCase(),
]
));
ul.dispatchEvent(new Event('change'));
arr.filter(RegExp.prototype.test.bind(/^[рим]+$/i))
// или
arr.filter(n => !n.match(/[^рим]/i))
// или
arr.filter(n => !n.replace(/р|и|м/gi, ''))
// или
arr.filter(n => [...n.toLowerCase()].every(m => 'рим'.includes(m)))
const itemSelector = '.radio';
const activeClass = 'active';
// конечно, вы можете и дальше продолжать ковырять jquery
const $items = $(itemSelector).on('change', function() {
$items.next().removeClass(activeClass);
$(this).next().addClass(activeClass);
});
// но ведь есть и другой путь
const items = document.querySelectorAll(itemSelector);
const onChange = ({ currentTarget: t }) =>
items.forEach(n => n.nextElementSibling.classList.toggle(activeClass, n === t));
items.forEach(n => n.addEventListener('change', onChange));
.radio:has(:checked) + .order__form-input {
/* сюда переносим стили, делающие input видимым */
}
arr.reduce((acc, n) => (
Object.entries(n.json_build_object).forEach(([ k, v ]) => {
(acc[k] ??= []).find(m => m.id === v.id) || acc[k].push(v);
}),
acc
), {})