$("#changeCityInput").bind("keyup change",
$('#changeCityInput').on('input',
const checked = Array.from(document.querySelectorAll('.btn:checked'), n => n.value);
const filtered = arr.filter(n => checked.includes(n));
const createList = arr =>
arr.reduceRight((acc, n) => ({
val: n,
next: acc,
}), null);
function createList(arr) {
let list = null;
for (let i = arr.length; i--;) {
list = {
val: arr[i],
next: list,
};
}
return list;
}
const createList = (arr, i = 0) =>
i < arr.length
? ({ val: arr[i], next: createList(arr, i + 1) })
: null;
button.addEventListener('click', () => {
anotherButton.click();
});
button.addEventListener('click', () => {
anotherButton.dispatchEvent(new Event('click', { bubbles: true }));
});
.push(x)
на .push([...x])
.function pyramid(n) {
const result = [];
for (let i = 0; ++i <= n;) {
const x = [];
for (let j = 0; ++j <= i; x.push(1)) ;
result.push(x);
}
return result;
}
const pyramid = length => Array.from({ length }, (_, i) => Array(i + 1).fill(1));
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))
);
}
});