document.addEventListener('click', updateCounter);
document.addEventListener('input', updateCounter);
document.querySelectorAll('.tariff__counter').forEach(n => {
const max = n.dataset.seats;
n.querySelectorAll('.tariff__counter-max').forEach(m => m.innerText = max);
n.querySelectorAll('.amount').forEach(m => m.max = max);
n.querySelectorAll('button').forEach(m => m.dataset.change = m.innerText === '+' ? 1 : -1);
});
function updateCounter({ target: t }) {
const input = t.closest('.tariff__counter-block')?.querySelector('.amount');
if (input) {
const { min, max, value } = input;
input.value = Math.max(min, Math.min(max, (value | 0) + (t.dataset.change | 0)));
}
}
const keys = [ 'id', 'secondId' ];
const result = firstArray.map(n => secondArray.find(m => keys.every(k => n[k] === m[k])) ?? n);
const arrToTree = (arr, keys) =>
arr.reduce((acc, n) => (
keys.reduce((p, c, i) => p[n[c]] ??= i + 1 === keys.length ? n : {}, acc),
acc
), {});
const keys = [ 'id', 'secondId' ];
const tree = arrToTree(secondArray, keys);
const result = firstArray.map(n => keys.reduce((p, c) => p?.[n[c]], tree) ?? n);
const arrToTree = (arr, keys) =>
arr.reduce((acc, n) => (
keys(n).reduce(
(p, c, i, a) => p.set(c, p.get(c) ?? (-~i === a.length ? n : new Map)).get(c),
acc
),
acc
), new Map);
const keys = n => [ n.id, n.secondId ];
const result = firstArray.map(function(n) {
return keys(n).reduce((p, c) => p?.get(c), this) ?? n;
}, arrToTree(secondArray, keys));
function getLeaves(tree) {
const result = [];
for (const stack = [...tree]; stack.length;) {
const n = stack.pop();
if (Array.isArray(n.children) && n.children.length) {
stack.push(...n.children);
} else {
result.push(n);
}
}
return result.reverse();
}
function getLeaves(tree) {
const result = [];
const stack = [];
for (let arr = tree, i = 0; i < arr.length || stack.length; i++) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else if (arr[i].children instanceof Array && arr[i].children.length) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, arr[i].children ];
} else {
result.push(arr[i]);
}
}
return result;
}
function getLeaves([...tree]) {
for (let i = 0; i < tree.length; i++) {
const c = tree[i].children;
if (c?.constructor === Array && c.length) {
tree.splice(i--, 1, ...c);
}
}
return tree;
}
const groupSum = (arr, idKey, ...sumKeys) =>
Object.values(arr.reduce((acc, n) => (
acc[n[idKey]] ??= sumKeys.reduce((group, k) => (
group[k] = 0,
group
), Object.assign(new n.constructor, n)),
sumKeys.forEach(k => acc[n[idKey]][k] += n[k]),
acc
), {}));
// ваш случай
const result = groupSum(arr, 'product', 'price', 'selling_price', 'quantity');
// элементам исходного массива не обязательно быть объектами, это могут быть и массивы
groupSum([
[ 'A', 1, 10 ],
[ 'A', 2, 20 ],
[ 'A', 3, 30 ],
[ 'B', 1, 5 ],
[ 'B', 10, 5 ],
[ 'B', 100, 5 ],
], 0, 1, 2) // [ [ 'A', 6, 60 ], [ 'B', 111, 15 ] ]
[
[ '.btn-all', 'click', onGetDataClick ],
[ '.elem button', 'click', onPlusMinusClick ],
[ '.amount', 'input', onAmountInput ],
].forEach(([ selector, type, handler ]) => {
document.querySelectorAll(selector).forEach(n => n.addEventListener(type, handler));
});
function onGetDataClick(e) {
const data = Array.prototype.flatMap.call(
e.target.closest('.child-block').querySelectorAll('.elem'),
n => Array(+n.querySelector('.amount').value).fill(+n.dataset.id)
);
console.log(data);
}
function onPlusMinusClick({ target }) {
const input = target.closest('.elem').querySelector('.amount');
input.value -= target.innerText === '+' ? -1 : 1;
input.dispatchEvent(new Event('input'));
}
function onAmountInput({ target: t }) {
t.value = Math.max(t.min, Math.min(t.max, t.value | 0));
}
const obj = {
a: {
b: {
c: {
xxx: 666,
},
},
},
};
const proxy = new Proxy(obj, {
get(target, key) {
return key.split('.').reduce((p, c) => p?.[c], target);
},
set(target, key, val) {
const keys = key.split('.');
const k = keys.pop();
keys.reduce((p, c) => p[c] ??= {}, target)[k] = val;
return true;
},
});
console.log(proxy['a.b.c.xxx']); // 666
proxy['x.y.z'] = 187;
console.log(obj.x.y.z); // 187
// имена свойств можно передавать в виде массива
const pick = (obj, keys) => Object.fromEntries(keys.map(n => [ n, obj[n] ]));
const newObj = pick(obj, [ 'b', 'c' ]);
// или как отдельные значения
const pick = (obj, ...keys) => keys.reduce((acc, n) => (acc[n] = obj[n], acc), {});
const newObj = pick(obj, 'b', 'c');
const pickExisting = (obj, keys) =>
Object.fromEntries(keys.filter(n => n in obj).map(n => [ n, obj[n] ]));
const pickOwn = (obj, keys) =>
keys.reduce((acc, n) => (Object.hasOwn(obj, n) && (acc[n] = obj[n]), acc), {});
const pick = (obj, filterFn) => Object.fromEntries(Object.entries(obj).filter(filterFn));
const obj1 = pick(obj, ([ k, v ]) => 'abc'.includes(k) && v % 2); // {a: 1, c: 3}
const obj2 = pick(obj, n => n[1] > 2); // {c: 3, d: 5}
nextSlide() {
---> nextSlide = () => {
.onclick = this.nextSlide;
---> .onclick = () => this.nextSlide();
.onclick = this.nextSlide;
---> .onclick = this.nextSlide.bind(this);
this
. str.split(/(?<=\S)\s*(?=[А-ЯЁ])/).join(' ')
// или
str.replace(/(?<=\S)(?=[А-ЯЁ])/g, ' ')
// или
str.replace(/(\S)(?=[А-ЯЁ])/g, '$1 ')
// или
str.replace(/[А-ЯЁ]/g, (m, i) => i && str[~-i] !== ' ' ? ' ' + m : m)
.filter(function (el, i) { return arr[i] === el[i]; })
0
? Или 5
? А зачем тогда [i]
? Может, должно было быть arr[i] === el
? const searchOptions = [
[ '#search_table', tr => $('input[name^=name]', tr).val() ],
[ '#search_card', tr => $('[data-item-name="name"]', tr).text() ]
];
$(searchOptions.map(n => n[0]).join(', ')).on('input', () => {
const values = searchOptions.map(n => $(n[0]).val().toLowerCase());
$('#tabname tbody tr')
.hide()
.filter((i, n) => searchOptions.every((m, j) => m[1](n).toLowerCase().includes(values[j])))
.show();
});
const sorted = (arr, key) => arr
.map(n => [ key(n), n ])
.sort(([a], [b]) => a < b ? -1 : +(a > b))
.map(n => n[1]);
const sortedArr = sorted(arr, n => new Date(n.replace(/(\d+)\.(\d+)\.(\d+),/, '$3-$2-$1')));
// или
const sortedArr = sorted(arr, n => n.replace(/.+(?=,)/, m => m.split('.').reverse().join('')));
`${arr}`.match(/\b\w{5}\b/g) || []
// или
arr.reduce((acc, n) => (n.length ^ '0b101' || acc.push(n), acc), [])
// или
arr.filter(n => n[4] && !n[-~4])
// или
arr.filter(RegExp.prototype.test.bind(/^.....$/))
// или
arr.reduce((acc, n) => ((acc[n.search('$')] ??= []).push(n), acc), {})[5] ?? []
// или
(function xxx(arr, i = 0) {
return arr.hasOwnProperty(i)
? [].concat(5 - [].push(...arr[i]) ? [] : arr[i], xxx(arr, i + 1))
: [];
})(arr)
instanceof Object
.true
или false
.function getNestedData(data, test) {
const result = [];
for (const stack = [ data ]; stack.length;) {
const n = stack.pop();
if (n instanceof Object) {
stack.push(...Object.values(n).reverse());
}
if (test(n)) {
result.push(n);
}
}
return result;
}
console.log(getNestedData(tree, Number.isFinite));
const firstNonRepeatingLetter = ([...str]) => Object
.values(str.reduce((acc, n, i) => ((acc[n.toLowerCase()] ??= [ 0, i, n ])[0]++, acc), {}))
.reduce((min, n) => (n[0] === 1 && n[1] < min[1] ? n : min), [ 0, Infinity, '' ])
.pop();
const firstNonRepeatingLetter = str =>
str.charAt(Array
.from(str.toLowerCase())
.findIndex((n, i, a) => a.indexOf(n) === a.lastIndexOf(n))
);
async function() {
let result = null;
while (1) {
result = await fetch(...);
if (result тот, который нужен) {
break;
}
await new Promise(r => setTimeout(r, 5000));
}
return result;
}
const sum = data =>
Array.isArray(data)
? data.reduce((acc, n) => acc + sum(n), 0)
: (+data || 0);
function sum(data) {
let result = 0;
for (const stack = [ data ]; stack.length;) {
const n = stack.pop();
if (n instanceof Array) {
stack.push(...n);
} else {
result += +n || 0;
}
}
return result;
}
true
, '0xBB'
, { valueOf: () => 666 }
и т.д.