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.flat().reduce((acc, n) => (
Object.assign(acc[n[key]] ??= {}, n),
acc
), {}));
const result = merge('id', sum, arr1, arr2);
const merge = (key, ...arrs) =>
Array.from(arrs.reduce((acc, arr) => arr.reduce((acc, n) => {
const k = key(n);
return acc.set(k, Object.assign(acc.get(k) ?? {}, n));
}, acc), 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), []);
app.ifScroll =
ifScroll.value =
. document.querySelectorAll('.parent').forEach((n, i) => {
n.insertAdjacentHTML('beforeend', `<div class="child">${arr[i]}</div>`);
});
for (const [ i, n ] of document.querySelectorAll('.parent').entries()) {
n.append(document.createElement('div'));
n.lastChild.className = 'child';
n.lastChild.innerText = arr[i];
}
arr.forEach(function(n, i) {
const div = document.createElement('div');
div.classList.add('child');
div.textContent = n;
this[i].appendChild(div);
}, document.getElementsByClassName('parent'));
$('.parent').append(i => `<div class="child">${arr[i]}</div>`);
const [ checked, setChecked ] = React.useState(false);
<input
type="checkbox"
checked={checked}
onChange={e => setChecked(e.target.checked)}
...
<button
disabled={!checked}
...
нет примера их использования
<q-select
ref="select"
...
<q-btn
@click="$refs.select.showPopup()"
...
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'));
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
length = len(matrix)
for i in range(0, length // 2):
for j in range(i, length - i - 1):
matrix[i][j], \
matrix[j][length - i - 1], \
matrix[length - i - 1][length - j - 1], \
matrix[length - j - 1][i] \
= \
matrix[length - j - 1][i], \
matrix[i][j], \
matrix[j][length - i - 1], \
matrix[length - i - 1][length - j - 1]
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 result = Object.values(data.reduce((acc, n) => (
(acc[n.brand] ??= { ...n, price: 0 }).price += n.price,
acc
), {}));
function uniqueWithSum(data, key, sumKey) {
const getKey = key instanceof Function ? key : n => n[key];
const unique = new Map;
for (const n of data) {
const k = getKey(n);
unique
.set(k, unique.get(k) ?? Object.assign(new n.constructor, n, { [sumKey]: 0 }))
.get(k)[sumKey] += n[sumKey];
}
return unique;
}
// ваш случай
const result = [...uniqueWithSum(data, 'brand', 'price').values()];
// элементам исходного массива не обязательно быть объектами
Array.from(uniqueWithSum([
[ 'aaa', 1 ],
[ 'aaa', 10 ],
[ 'aaa', 100 ],
[ 'bbb', 666 ],
], 0, 1).values()) // [ [ 'aaa', 111 ], [ 'bbb', 666 ] ]