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) {
const stack = [];
let result = 0;
for (let i = 0, arr = [ data ]; i < arr.length || stack.length; i++) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else if (arr[i] instanceof Array) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, arr[i] ];
} else {
result += +arr[i] || 0;
}
}
return result;
}true, '0xBB', { valueOf: () => 666 } и т.д.
Странно, но все работает, несмотря на ошибку:
TypeError: Cannot read properties of null (reading 'insertAdjacentHTML').
arr.forEach(n => {
const el = document.getElementById(n.id);
if (el) {
el.innerHTML = `
<h2>Id: ${n.id}</h2>
<h3>${n.title}</h3>
<p>${n.body}</p>
`;
}
});for (const { id, title, body } of arr) {
document.querySelector(`[id="${id}"]`)?.insertAdjacentHTML('beforeend', `
<h2>Id: ${id}</h2>
<h3>${title}</h3>
<p>${body}</p>
`);
}section изначально будет пустым):document.querySelector('section').innerHTML = arr
.map(n => `
<div id="post-${n.id}">
<h2>Id: ${n.id}</h2>
<h3>${n.title}</h3>
<p>${n.body}</p>
</div>`)
.join('');const limit = document.querySelector('section').children.length;
const requestURL = `https://jsonplaceholder.typicode.com/posts?_limit=${limit}`;const requestURL = 'https://jsonplaceholder.typicode.com/posts?' + Array
.from(document.querySelector('section').children, n => `id=${n.id}`)
.join('&');
const elements = document.querySelectorAll('[name^=AR_AMOUNT]');const sum = Array.prototype.reduce.call(
elements,
(acc, n) => acc + +n.value,
0
);
// или
let sum = 0;
for (const { value } of elements) {
sum += Number(value);
}
// или
let sum = 0;
for (let i = 0; i < elements.length; i++) {
sum = sum + elements.item(i).value * 1;
}0:const sum = (function sum(i, n = elements[i]) {
return n ? parseFloat(n.value) + sum(i + 1) : 0;
})(0);+, в строку; строку отдаём в eval; всё, сумма получена (ну, почти, если исходная коллекция элементов была пуста, то строка тоже будет пустой, так что надо не забыть подставить 0 вместо возможного undefined, который является результатом выполнения пустой строки):const sum = eval(Array.from(elements, n => n.value).join('+')) ?? 0;
// заменяем содержимое элемента main
main.innerHTML = arr.reduceRight(
(content, tag) => `<${tag}>${content}</${tag}>`,
''
);
// или, дополняем его
main.insertAdjacentHTML(
'beforeend',
(function next(i, tag = arr[i] ?? '') {
return tag && `<${tag}>${next(-~i)}</${tag}>`;
})(0)
);// замена контента
main.replaceChildren(...arr.reduceRight((content, tag) => {
const el = document.createElement(tag);
el.append(...content);
return [ el ];
}, []));
// или, добавление
arr.reduce((el, tag) => (
el.appendChild(document.createElement(tag)),
el.lastChild
), main);
const merge = (target, ...sources) =>
sources.reduce((acc, n) => (
Object.entries(n).forEach(([ k, v ]) =>
acc[k] = v instanceof Object
? merge(acc[k] instanceof Object ? acc[k] : {}, v)
: v
),
acc
), target);
const result = merge({}, ...arrayObj);
const sorted = (data, key) => Array
.from(data, n => [ key(n), n ])
.sort(([a], [b]) => a < b ? -1 : +(a > b))
.map(n => n[1]);const sortChildren = (el, key) =>
el.append(...sorted(el.children, key));<button data-order="-1">От большего к меньшему</button>
<button data-order="+1">От меньшего к большему</button>.catalog-items (вес элемента - число внутри, умноженное на направление сортировки), кликнутой кнопке класс добавляем, у остальных убираем:const wrapper = document.querySelector('.catalog-items');
const buttons = document.querySelectorAll('[data-order]');
buttons.forEach(n => n.addEventListener('click', onClick));
function onClick({ target: t }) {
const order = +t.dataset.order;
sortChildren(wrapper, el => parseInt(el.innerText) * order);
buttons.forEach(n => n.classList.toggle('active', n === t));
}
- $('.play').attr('data-play', video);
+ $('.play').data('play', video);- video = $(this).data('video');
+ video = $(this).attr('data-video');
- atplay = $(this).data('play');
+ atplay = $(this).attr('data-play');data-* attributes are used to initialize jQuery data. An element's data-* attributes are retrieved the first time the data() method is invoked upon it, and then are no longer accessed or mutated
const play = document.querySelector('.play');
document.querySelectorAll('.paskal').forEach(function(n) {
n.addEventListener('click', this);
}, e => play.dataset.play = e.currentTarget.dataset.video);
play.addEventListener('click', e => {
console.log(e.currentTarget.dataset.play);
});
const [ zero, one, two, three, four, five, six, seven, eight, nine ] = Array.from(
{ length: 10 },
(_, i) => f => f instanceof Function ? f(i) : i
// или
// (_, i) => f => f?.(i) ?? i
);
const plus = a => b => b + a;
const minus = a => b => b - a;
const times = a => b => b * a;
const dividedBy = a => b => b / a | 0;
const sortDigits = num => +[...`${num}`].sort((a, b) => b - a).join('');const sortDigits = num => ''.concat.apply('', num.toString().split('').sort().reverse()) - 0;const sortDigits = num => Number(Array
.from('' + num)
.reduce((acc, n) => (acc[n]++, acc), Array(10).fill(0))
.reduceRight((acc, n, i) => acc + String(i).repeat(n), '')
);const sortDigits = num => Array
.prototype
.reduce
.call(String(num), (acc, n) => ((acc[9 - n] ??= []).push(n | 0), acc), [])
.flat()
.reduce((acc, n) => acc * 10 + n, 0);
const statsMeta = [
{ title: 'отредактированные', count: item => +item.edited },
{ title: 'неотредактированные', count: item => +!item.edited },
{ title: 'всего', count: () => 1 },
];
const statsData = allMessages.reduce((acc, n) => (
statsMeta.forEach((m, i) => acc[i] += m.count(n)),
acc
), Array(statsMeta.length).fill(0));
console.log(statsMeta.map((n, i) => `${n.title}: ${statsData[i]}`).join('\n'));
const classPrefix = 'modal--';Array.from(el.classList).forEach(n => el.classList.toggle(n, !!n.indexOf(classPrefix)));el.classList.remove(...[...el.classList].filter(n => n.startsWith(classPrefix)));for (let i = el.classList.length; i--;) {
if (el.classList[i].search(classPrefix) === 0) {
el.classList.remove(el.classList[i]);
}
}el.classList.value = el.classList.value
.split(' ')
.filter(RegExp.prototype.test.bind(RegExp(`^(?!${classPrefix})`)))
.join(' ');el.className = el.className.replace(RegExp(`(^| )${classPrefix}\\S*`, 'g'), '').trim();
const result = arr1.filter(function(n) {
return !this.has(n[0]);
}, new Set(arr2.map(n => n[0])));function diff(data1, data2, compare = (a, b) => a === b) {
const arr = Array.isArray(data2) ? data2 : [...data2];
const result = [];
for (const n of data1) {
if (!arr.some(m => compare(m, n))) {
result.push(n);
}
}
return result;
}
const result = diff(
arr1,
arr2,
(a, b) => a.length === b.length && a.every((n, i) => Object.is(n, b[i]))
);const diff = function*(data1, data2, keys = n => n) {
const tree = new Map;
for (const n of data2) []
.concat(keys(n))
.reduce((p, c) => p.set(c, p.get(c) ?? new Map).get(c), tree)
.set(this, true);
for (const n of data1) {
if (![].concat(keys(n)).reduce((p, c) => p?.get(c), tree)?.get(this)) {
yield n;
}
}
}.bind(Symbol());
const result = [...diff(arr1, arr2)];
const result = arr2.map(function(n) {
return Object.fromEntries(this.map(m => [ m[1], n[m[0]] ]));
}, arr1.flatMap(Object.entries));const keys = Object.entries(Object.assign({}, ...arr1));
const result = arr2.map(n => keys.reduce((acc, m) => (acc[m[1]] = n[m[0]], acc), {}));
const xxx = str => Array
.from(str, (n, i) => n.toUpperCase() + n.toLowerCase().repeat(i))
.join('-');const xxx = str => str
.toUpperCase()
.split('')
.reduce((acc, n, i) => `${acc}${i ? '-' : ''}${n}${Array(-~i).join(n.toLowerCase())}`, '');const xxx = str => str
.toUpperCase()
.replace(/(?<=.)./g, (m, i) => '-'.concat(m, ...Array(i).fill(m.toLowerCase())));
const hidden = (str, count = 4) =>
'*'.repeat(count) + str.slice(-4);const hidden = (str, count = 4) =>
str.replace(/.*?(?=.{0,4}$)/, Array(count + 1).join('*'));
function sum(data, key = n => n) {
const getVal = key instanceof Function ? key : n => n[key];
let result = 0;
for (const n of data) {
result += getVal(n);
}
return result;
}const form = document.querySelector('form');
const result = form.querySelector('.result');
form.addEventListener('change', onChange);
form.dispatchEvent(new Event('change'));function onChange() {
result.textContent = sum(
this.querySelectorAll(':checked'),
n => +n.getAttribute('rel')
);
}
// или
function onChange(e) {
result.innerText = sum(
e.currentTarget.elements,
n => n.attributes.rel.value * n.checked
);
}