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);
}
preg_match_all('/\d+/', $str, $matches);
$sum = array_sum($matches[0]);
// или
$sum = 0;
foreach (preg_split('/\D+/', $str) as $n) {
$sum += intval($n);
}
id="mse2_ms|price_0"
|
засунуть в id.#
, а как значение атрибута, т.е. [id="mse2_ms|price_0"]
. const values = arr.length
? arr[0].filter(n => arr.every(m => m.includes(n)))
: [];
const values = (arr[0] || []).filter(function(n) {
return this.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;
}
}
}
const className = 'skiptranslate';
.for (const { childNodes: n } of document.getElementsByClassName(className)) {
for (let i = n.length; i--;) {
if (n[i].nodeType === Node.TEXT_NODE) {
n[i].remove();
}
}
}
document.querySelectorAll(`.${className}`).forEach(n => {
const nodes = [...n.children];
n.innerHTML = '';
n.append(...nodes);
});
function setVal(obj, path, val) {
const keys = path.split('.');
const key = keys.pop();
keys.reduce((p, c) => p[c] = p[c] || {}, obj)[key] = val;
return obj;
}
function replaceObjWithArr(obj) {
if (obj instanceof Object) {
const keys = Object.keys(obj).sort((a, b) => a - b);
obj = keys.every((n, i) => +n === i) ? keys.map(n => obj[n]) : obj;
keys.forEach(n => obj[n] = replaceObjWithArr(obj[n]));
}
return obj;
}
const output = replaceObjWithArr(Object
.entries(input)
.reduce((acc, n) => setVal(acc, ...n), {})
);
$('a').click(function(e) {
e.preventDefault();
$('html').animate({
scrollTop: $($(this).attr('href')).offset().top,
}, 500);
});