const maxStr = arr.length
? arr.reduce((max, n) => +n < +max ? max : n)
: null;function max(data, key = n => n) {
const getVal = key instanceof Function ? key : n => n[key];
let result = null;
for (const n of data) {
const val = getVal(n);
result = result?.[1] >= val ? result : [ n, val ];
}
return result?.[0];
}
const maxStr = max(arr, Number);
data.flatMap(item => item.events.flatMap(event => event.params.map(param => ({
name: item.name,
event_key: event.event_key,
...param,
}))))
const className = 'heading';
const wrapperTag = 'span';
const wrapCount = 3;document.querySelectorAll(`.${className}`).forEach(n => {
const words = n.innerText.split(' ');
const iMin = Math.max(0, Math.floor((words.length - wrapCount) / 2));
const iMax = Math.min(words.length - 1, iMin + wrapCount - 1);
words[iMin] = `<${wrapperTag}>${words[iMin]}`;
words[iMax] = `${words[iMax]}</${wrapperTag}>`;
n.innerHTML = words.join(' ');
});for (const n of document.getElementsByClassName(className)) {
const words = n.textContent.split(/(?= )/);
const wrapper = document.createElement(wrapperTag);
wrapper.textContent = words
.splice(Math.max(0, (words.length - wrapCount) >> 1), wrapCount, wrapper)
.join('');
n.replaceChildren(...words);
}
function fadeToggle(selector, delay) {
let index = -1;
return setInterval($items => {
$items.eq(index).fadeOut('slow');
index = (index + 1) % $items.length;
$items.eq(index).fadeIn('slow');
}, delay, $(selector));
}
const intervalId = fadeToggle('.sloi', 1000);
for (let i = begin; i <= end; i++) {
let str = '';
if (!(i % 3)) {
str += 'Fizz';
}
if (!(i % 5)) {
str += 'Buzz';
}
console.log(str || i);
}console.log(Array.from({ length: end - begin + 1 }, (_, i) => {
i += begin;
return (i % 3 ? '' : 'Fizz') + (i % 5 ? '' : 'Buzz') || i;
}).join('\n'));
// или
for (let i = ~-begin; ++i <= end;) {
console.log('FizzBuzz'.slice(i % 3 && 4, 4 << !(i % 5)) || i);
}
const roots = [];
COLLECT_ROOTS:
for (const n of arr) {
for (const m of arr) {
if (m.id === n.root_id) {
continue COLLECT_ROOTS;
}
}
roots.push(n);
}
// или
const roots = arr.filter(function(n) {
return !this.has(n.root_id);
}, new Set(arr.map(n => n.id)));
// или
const roots = (function get(i, n = arr[i]) {
return n
? [].concat(arr.every(m => m.id !== n.root_id) ? n : [], get(-~i))
: [];
})(0);function createTree({
data,
key = 'id',
parentKey = 'parentId',
childrenKey = 'children',
}) {
const tree = Object.fromEntries(data.map(n => [
n[key],
{ ...n, [childrenKey]: [] },
]));
return Object.values(tree).filter(n => (
!tree[n[parentKey]]?.[childrenKey].push(n)
));
}const tree = createTree({
data: arr,
parentKey: 'root_id',
});
if(sortedArr[i + 1] == sortedArr[i]) { results.push(sortedArr[i]); }
const getDuplicates = arr => arr
.slice()
.sort()
.reduce((acc, n, i, a) => (n === a[i + 1] && n !== a[i - 1] && acc.push(n), acc), []);const getDuplicates = arr => Array
.from(arr.reduce((acc, n) => acc.set(n, acc.has(n)), new Map))
.reduce((acc, n) => (n[1] && acc.push(n[0]), acc), []);const getDuplicates = arr =>
arr.reduce((acc, n) => (
(acc[1][n] = -~acc[1][n]) === 2 && acc[0].push(n),
acc
), [ [], {} ])[0];const getDuplicates = arr =>
[...arr.reduce((acc, n) => (
acc[+acc[0].has(n)].add(n),
acc
), [ new Set, new Set ])[1]];const getDuplicates = arr =>
[...new Set(arr.filter((n, i, a) => a.includes(n, i + 1)))];const getDuplicates = arr => arr
.filter((n, i, a) => i !== a.indexOf(n))
.filter((n, i, a) => i === a.indexOf(n));
const result = [];
for (const k in obj) {
if (obj.hasOwnProperty(k)) {
result.push([ k, typeof obj[k] ]);
}
}typeof):const result = Object
.entries(obj)
.map(function(n) {
return [ n[0], this(n[1]) ];
}, x => x?.constructor.name ?? `${x}`);
0 (например, для [ -1, 0, 0.1, 2 ] выдаёт 2 вместо 0.1). В первой части условия следует вместо предыдущего элемента массива смотреть индекс текущего - единственным неподходящим является нулевой.find. Для подмены undefined на null вообще не нужно никаких проверок делать - с этим справится nullish coalescing. Так что вот:const firstNonConsecutive = arr => arr.find((n, i, a) => i && a[i - 1] !== n - 1) ?? null;
arr.splice(0, arr.length, ...arr.map((n, i, a) => (a[i - 1] ?? 0) + (a[i + 1] ?? 0)));
const $links = $('.small a');
let currentIndex = null;
function setActiveImage(index) {
currentIndex = (index + $links.length) % $links.length;
$('.big img').attr('src', $links.eq(currentIndex).attr('href'));
$('.photo').text(`${currentIndex + 1} / ${$links.length}`);
}
$links.click(e => (e.preventDefault(), setActiveImage($links.index(e.currentTarget))));
$('#prev').click(() => setActiveImage(currentIndex - 1));
$('#next').click(() => setActiveImage(currentIndex + 1));
setActiveImage(0);
const select = document.querySelector('select');
const reg = /^\d\d\. /;const mustBeHidden = el => !reg.test(el.text);
// или
const mustBeHidden = el => el.textContent.search(reg) !== 0;
// или
const mustBeHidden = el => el.innerText.match(reg) === null;
// или
const mustBeHidden = el => !~-el.innerHTML.split(reg).length;const toggle = el => el.hidden = mustBeHidden(el);
// или
const toggle = el => el.style.display = mustBeHidden(el) ? 'none' : '';
// или
const toggle = el => el.style.setProperty('display', mustBeHidden(el) ? 'none' : '');
// или
const toggle = el => el.style.cssText += `display: ${mustBeHidden(el) ? 'none' : 'block'}`;
// или
const toggle = el => el.setAttribute('style', mustBeHidden(el) ? 'display: none' : '');
// или (надо будет добавить в стили .hidden { display: none; })
const toggle = el => el.classList.toggle('hidden', mustBeHidden(el));Array.prototype.forEach.call(select.options, toggle);
// или
for (const n of select.children) {
toggle(n);
}
// или
for (let i = 0; i < select.length; i++) {
toggle(select[i]);
}
// или
(function next(i, n = select.item(i)) {
n && (toggle(n), next(-~i));
})(0);
// или
select.querySelectorAll('option').forEach(toggle);
const newData = data
.reduce((acc, { type, ...n }) => (
(acc[acc.length - 1]?.[0] !== type) && acc.push([ type, [] ]),
acc[acc.length - 1][1].push(n),
acc
), [])
.map(([ type, children ]) => children.length > 1
? { type: `Section${type}`, children }
: { type, ...children[0] }
);
const count = str => [...str]
.reduce((acc, n, i, a) => (
a[i - 1] !== n && acc.push([ n, 0 ]),
acc[acc.length - 1][1]++,
acc
), [])
.flat()
.join('');const count = str => str.replace(/(.)\1*/g, m => m[0] + m.length);
const parseDate = str =>
new Date(str.split(' ', 1)[0].split('.').reverse().join('-'));
// или
const parseDate = str =>
new Date(str.replace(/(\d+)\.(\d+)\.(\d+)(.+)/, '$3-$2-$1'));
// или
const parseDate = str =>
(str = str.match(/\d+/g), new Date(str[2], ~-str[1], str[0]));const result = parseDate(str).toLocaleString('ru-RU', {
month: 'long',
day: 'numeric',
});