const filterObject = (obj, values) =>
Object.entries(obj).reduce((acc, [ k, v ]) => (
values.indexOf(v) !== -1 && (acc[k] = v),
acc
), {});
const result = filterObject(a, b);const filterObject = (obj, filter) =>
Object.fromEntries(Object.entries(obj).filter(n => filter(...n)));
const result = filterObject(a, (k, v) => b.includes(v));
Объект FileReader позволяет веб-приложениям асинхронно читать содержимое файлов
onFileChange({ target: { files: [ file ] } }) {
if (file) {
const reader = new FileReader();
reader.addEventListener('load', e => {
this.fileinput = e.target.result;
console.log(this.fileinput);
});
reader.readAsText(file);
}
},
const flat = arr =>
(arr || []).reduce((acc, { children, ...n }) => {
if (n.isExpanded || !children) {
acc.push(n, ...flat(children));
} else {
acc.push({ ...n, children });
}
return acc;
}, []);isExpanded: false у кого-то из предков уровнем выше родительского, тоconst flat = arr =>
(arr || []).reduce((acc, { children, ...n }) => {
const flatChildren = flat(children);
if (n.isExpanded || !children) {
acc.push(n, ...flatChildren);
} else {
acc.push({ ...n, children: flatChildren });
}
return acc;
}, []);
this.update = () => {
const w = this.w / 2;
const h = this.h / 2;
this.x = Math.max(w, Math.min(W - w, this.x + this.dx));
this.y = Math.max(h, Math.min(H - h, this.y + this.dy));
};document.addEventListener('keydown', e => {
switch (e.key) {
case 'ArrowLeft': pl.dx = -pl.speed; break;
case 'ArrowRight': pl.dx = pl.speed; break;
case 'ArrowUp': pl.dy = -pl.speed; break;
case 'ArrowDown': pl.dy = pl.speed; break;
}
});
document.addEventListener('keyup', e => {
switch (e.key) {
case 'ArrowLeft':
case 'ArrowRight': pl.dx = 0; break;
case 'ArrowUp':
case 'ArrowDown': pl.dy = 0; break;
}
});
const tableId = 'news';
const trSelector = 'tbody tr';$(`#${tableId}`).show().not(`:has(${trSelector})`).hide();
// или
const $table = $('[id="' + tableId + '"]');
$table.toggle(!!$table.find(trSelector).length);(t => t.hidden = !t.querySelector(trSelector))
(document.querySelector('#'.concat(tableId)));
// или (в стили надо будет добавить .hidden { display: none; })
const table = document.getElementById(tableId);
table.classList.toggle('hidden', Array.prototype.every.call(
table.tBodies,
n => !n.rows.length
));#news:not(:has(tbody tr)) {
display: none;
}
const attacks = [
{ minChance: 7, damage: 40, name: 'critical' },
{ minChance: 5, damage: 20, name: 'big' },
{ minChance: 0, damage: 10, name: 'weak' },
];
const messages = {
start: (player, enemy) => `Welcome! Yor health is - ${player}%, your enemy health - ${enemy}%`,
end: (player, enemy) => `You ${enemy <= 0 ? 'win' : 'lost'}! Your hp level - ${player}, opponents hp level - ${enemy}`,
chance: (player, enemy) => `your chance - ${player}, your opponent chance - ${enemy}`,
turn: (player, enemy, hit, isEnemy) =>
`${isEnemy ? 'Enemy' : 'Your'} turn...
${isEnemy ? 'Enemy' : 'You'} did a ${hit} hit
${isEnemy ? 'Your' : 'Enemy'} hp - ${isEnemy ? player : enemy}`,
};
const simpleFight = () => {
const hp = [ 100, 100 ];
console.log(messages.start(...hp));
while (hp.every(n => n > 0)) {
const chances = hp.map(() => Math.random() * 11 | 0);
console.log(messages.chance(...chances));
if (chances[0] !== chances[1]) {
const chance = Math.max(...chances);
const attack = attacks.find(n => n.minChance < chance);
const isEnemyAttacks = chance === chances[1];
hp[+!isEnemyAttacks] -= attack.damage;
console.log(messages.turn(...hp, attack.name, isEnemyAttacks));
}
}
console.log(messages.end(...hp));
};
const sum = str.match(/\d+/g).reduce((acc, n) => acc + +n, 0);
// или
let sum = 0;
for (const n of str.split(/\D+/)) {
sum += Number(n);
}
// или
const sum = eval(str.replace(/\|(\d+)\|/g, '+$1'));preg_match_all('/\d+/', $str, $matches);
$sum = array_sum($matches[0]);
// или
$sum = 0;
foreach (preg_split('/\D+/', $str) as $n) {
$sum += intval($n);
}
// или
eval('$sum = '.preg_replace('/\|(\d+)\|/', '+$1', $str).';');
id="mse2_ms|price_0"| засунуть в id.#, а как значение атрибута, т.е. [id="mse2_ms|price_0"].
const values = (arr[0] || [])
.filter(n => arr.every(m => m.includes(n)))
.filter((n, i, a) => i === a.indexOf(n));const values = (([ set, ...sets ]) => {
return set ? [...set].filter(n => sets.every(m => m.has(n))) : [];
})(arr.map(n => new Set(n)));const values = Array
.from(arr
.flatMap(n => [...new Set(n)])
.reduce((acc, n) => acc.set(n, (acc.get(n) || 0) + 1), new Map))
.reduce((acc, n) => ((n[1] === arr.length) && acc.push(n[0]), acc), []);const values = Array
.from(arr.reduce((acc, n) => (
n.forEach(m => acc.set(m, acc.get(m) || new Set).get(m).add(n)),
acc
), new Map))
.reduce((acc, n) => (n[1].size === arr.length && acc.push(n[0]), acc), []);const values = [...arr.reduce((acc, n) => (
n = new Set(n),
acc.intersection?.(n) ?? n
), [])];
<select id="country"></select>
<select id="city"></select>const countryEl = document.querySelector('#country');
const cityEl = document.querySelector('#city');
countryEl.innerHTML = data
.map(n => `<option value="${n.id}">${n.country}</option>`)
.join('');
countryEl.addEventListener('change', function() {
cityEl.innerHTML = data
.find(n => n.id === this.value)
.cities
.map(n => `<option value="${n.id}">${n.city}</option>`)
.join('');
});
countryEl.dispatchEvent(new Event('change'));
const last = promises => new Promise((resolve, reject) => {
let pending = promises.length;
if (!pending) {
resolve();
} else {
promises.forEach(n => n
.then(result => --pending || resolve(result))
.catch(error => --pending || reject(error))
);
}
});
siteForm.userAdmin = loginValue === login && passwordValue === password;
const order = Object.fromEntries(gameTypeOrder.map((n, i) => [ n, i ]));res.sort((a, b) => order[a.game_status] - order[b.game_status]);const sortedRes = res
.reduce((acc, n) => (acc[order[n.game_status]].push(n), acc), gameTypeOrder.map(() => []))
.flat();
// или
const sorted = (arr, key) => arr
.map(n => [ n, key(n) ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);
const sortedRes = sorted(res, n => order[n.game_status]);
$('.gallery-colors :checked')
.parent()
.prevAll()
.find('input[type="radio"]:not(:disabled)')
.last()
.click()
str.slice(str.lastIndexOf('/') + 1, str.lastIndexOf('.'))
// или
str.split('/').pop().split('.').slice(0, -1).join('.')
// или
str.replace(/.+\//, '').replace(/\.[^.]+$/, '')
// или
str.match(/(?<=\/)[^/]+(?=\.[^.]+$)/)[0]
// или
str.match(/\/([^/]+)\.[^.]+$/)[1]
$('button.prev').click(function() {
$('.slide:last').prependTo($('.slider'));
$('.slider').css('margin-left', '-100%').animate({
marginLeft: '+=100%'
}, 500);
});
$(document).on('click', function(e) {
e.preventDefault();
const $submenu = $(e.target).closest('li').children('.submenu');
$submenu.fadeToggle();
$('.nav li ul').not($submenu).fadeOut();
});
const table = document.querySelector('здесь селектор вашей таблицы');
const idAttr = 'id-object';
const propAttr = 'object-name';const data = Array.prototype.reduce.call(
table.querySelectorAll('table tbody tr'),
(acc, tr) => (
tr.querySelectorAll(`[${propAttr}]`).forEach(function(td) {
this[td.getAttribute(propAttr)] = td.innerText;
}, acc[tr.querySelector(`[${idAttr}]`).getAttribute(idAttr)] = {}),
acc
),
{}
);
// или
const data = {};
for (const { rows } of table.tBodies) {
for (const { cells } of rows) {
const item = data[cells[0].attributes[idAttr].value] = {};
for (let i = 1; i < cells.length; i++) {
const td = cells[i];
item[td.attributes[propAttr].value] = td.textContent;
}
}
}