this.getRandomZ() не вычисляется
const getRandomPolynom = () => {
const [ A, B, C, D ] = Array.from({ length: 4 }, this.getRandomZ);
return x => A * x ** 4 + B * x ** 3 - C * x ** 2 - D * x + 10;
};
const containerSelector = '.card';
const selectSelector = `${containerSelector} select`;
const dataAttr = 'name';
$(selectSelector).change(function() {
$(this)
.closest(containerSelector)
.find(`[data-${dataAttr}]`)
.hide()
.filter(`[data-${dataAttr}="${this.value}"]`)
.show();
}).val(defaultValueSelected).trigger('change');
// или
const selects = document.querySelectorAll(selectSelector);
const onChange = ({ target: t }) => t
.closest(containerSelector)
.querySelectorAll(`[data-${dataAttr}]`)
.forEach(n => n.style.display = t.value === n.dataset[dataAttr] ? 'block' : 'none');
selects.forEach(n => {
n.value = defaultValueSelected;
n.addEventListener('change', onChange);
n.dispatchEvent(new Event('change'));
});
Array
.from(document.querySelectorAll('tr > td:last-child'))
.filter((n, i, a) => n.innerText !== a[~-i]?.innerText)
.forEach(n => n.innerHTML = `<a href="#">${n.innerText}</a>`);
let prev = null;
for (const { rows } of document.querySelector('table').tBodies) {
for (const { lastElementChild: n } of rows) {
const curr = n.textContent;
if (curr !== prev) {
n.innerHTML = '<a href="#">' + (prev = curr) + '</a>';
}
}
}
// создаём новый массив
const newArr = arr.map(({ name, ...n }) => (n.user_name = name, n));
// изменяем существующий:
arr.forEach(n => (n.user_name = n.name, delete n.name));
// keys - объект вида { старый_ключ_1: 'новый_ключ_1', старый_ключ_2: 'новый_ключ_2', ... }
const renameKeys = (obj, keys) =>
Object.fromEntries(Object
.entries(obj)
.map(([ k, v ]) => [ keys.hasOwnProperty(k) ? keys[k] : k, v ])
);
const newArr = arr.map(n => renameKeys(n, { name: 'user_name' }));
function renameKeys(obj, keys) {
for (const n of Object.entries(keys)) {
if (obj.hasOwnProperty(n[0])) {
obj[n[1]] = obj[n[0]];
delete obj[n[0]];
}
}
}
arr.forEach(n => renameKeys(n, { name: 'user_name' }));
const isSumEven = arr => arr.reduce((p, c) => p ^ c, 1) & 1;
// или
const isSumEven = arr => !(arr.filter(n => n % 2).length % 2);
// или
const isSumEven = arr => Number.isInteger(arr.reduce((acc, n) => acc + n, 0) / 2);
// или
const isSumEven = arr => /[02468]$/.test(eval(arr.join('+')) ?? 0);
const result = arr.filter(isSumEven);
. function split(arr, numParts) {
const partSize = arr.length / numParts | 0;
return Array
.from({ length: numParts }, (n, i) => i * partSize)
.map((n, i, a) => arr.slice(n, a[i + 1]));
}
function split(arr, numParts) {
const partSize = arr.length / numParts | 0;
const numLooseItems = arr.length % numParts;
return Array.from(
{ length: numParts },
function(_, i) {
return arr.slice(this(i), this(i + 1));
},
i => i * partSize + Math.min(i, numLooseItems)
);
}
coords.reduce((acc, n, i, a) => (
acc.push(n),
(n.line !== a[i + 1]?.line) && acc.push({ ...n, value: 0 }),
acc
), [])
coords.flatMap((n, i, a) =>
i === ~-a.length || n.line !== a[-~i].line
? [ n, { ...n, value: 0 } ]
: n
)
const data = Array.prototype.reduce.call(
document.querySelector('form').elements,
(acc, n) => {
const keys = n.name.match(/\w+/g);
const key = keys.pop();
keys.reduce((p, c) => p[c] ??= {}, acc)[key] = n.value;
return acc;
},
{}
);
Для
<input type="text" name="iuowye[rrr][]" value="1"> <input type="text" name="iuowye[rrr][]" value="2"> <input type="text" name="iuowye[rrr][]" value="3">
работать не будет.
const data = Array
.from(document.querySelectorAll('form [name]'))
.reduce((acc, { name, value }) => {
const keys = name.match(/\w+|\[\w*\]/g).map(n => n.replace(/^\[|\]$/g, ''));
const key = keys.pop();
const isArr = !key;
const values = keys.reduce((p, c, i, a) => {
return p[c] ??= (i === a.length - 1 && isArr ? [] : {});
}, acc);
values[isArr ? values.length : key] = value;
return acc;
}, {});
function sum(...v1) {
const s = v1.reduce((acc, n) => acc + n, 0);
const f = (...v2) => v2.length ? sum(...v2, s) : s;
return v1.length ? f : s;
}
const selector = '.text';
const regex = /@(\w+)/g;
const replacement = '<a href="https://site.com/$1">$&</a>';
const replace = str => str.replace(regex, replacement);
$(selector).html((i, html) => replace(html));
// или
document.querySelectorAll(selector).forEach(n => {
n.innerHTML = replace(n.innerText);
});
return [...el].map((n) => new Select(n));
Select
на this.constructor
. const checkedTexts = (el, selector) =>
Array.from(el.querySelectorAll(`${selector}:checked`), n => n.parentNode.innerText);
const propertyText = (el, selector) =>
el.querySelector(selector).innerText.split(': ')[1];
document.querySelector('.container-filter').addEventListener('input', function() {
const maxPrice = parseInt(this.querySelector('.range').value);
const brands = checkedTexts(this, '.input');
const years = checkedTexts(this, '.input-date');
document.querySelectorAll('.device .laptop').forEach(n => {
const price = parseInt(propertyText(n, '.laptop-price'));
const brand = propertyText(n, '.laptop-name');
const year = propertyText(n, '.laptop-year');
n.style.display = (
(maxPrice >= price) &&
(!brands.length || brands.includes(brand)) &&
(!years.length || years.includes(year))
)
? 'block'
: 'none';
});
});
const newStr = str
.split(' ')
.map(function([...word]) {
const sorted = word.filter(this).sort((a, b) => b.localeCompare(a));
return word.map(n => this(n) ? sorted.pop() : n).join('');
}, RegExp.prototype.test.bind(/[a-z]/i))
.join(' ');
str.replace(/(\d{2})(\d{2})/, '$1.$2.')
// или
str.replace(/(?=\d{4}$|\d{6}$)/g, '.')
// или
str.match(/(..)(..)(.+)/).slice(1).join('.')
// или
[ 0, 2, 4 ].map((n, i, a) => str.slice(n, a[i + 1])).join`.`
// или
[...str].reduce((acc, n, i) => acc + n + ([ ,'.',,'.' ][i] || ''))
// или
''.concat(...Array.from(str, (n, i) => '24'.includes(i) ? `.${n}` : n))
document.querySelector('table').addEventListener('click', ({ target: t }) => {
if (t.classList.contains('save_order')) {
const tr = t.closest('tr'); // всё, идентифицировали
}
});
arr.pop();
// или
arr.length -= !!arr.length;
// или
arr.splice(-1);
const count = сколько надо удалить;
):for (let i = count; --i >= 0 && arr.length; arr.pop()) ;
// или
arr.length -= Math.max(0, Math.min(arr.length, count));
// или
count > 0 && arr.splice(-count);