function chunked(str, numChunks) {
const chunkSize = Math.ceil(str.length / numChunks);
return Array.from(
{ length: numChunks },
(_, i) => str.slice(i * chunkSize, (i + 1) * chunkSize)
);
}неаккуратненько как-то:
chunked('test', 3) // [ "te", "st", "" ]
const chunked = (str, numChunks) =>
Array.from(
{ length: numChunks },
function(_, i) {
return str.slice(this(i), i < ~-numChunks ? this(-~i) : str.length);
},
i => i * (Math.max(1, str.length / numChunks | 0))
);function chunked(str, numChunks) {
const chunkSize = str.length / numChunks | 0;
const numLooseItems = str.length % numChunks;
const chunkIndex = i => i * chunkSize + Math.min(i, numLooseItems);
return Array.from(
{ length: numChunks },
(_, i) => str.slice(chunkIndex(i), chunkIndex(++i))
);
}
const newStr = str.replace(/\d.*/, '');
// или
const newStr = str.match(/^\D*/)[0];
// или
const newStr = str.split(/[0-9]/).shift();
// или
const newStr = str.slice(0, str.search(/\d|$/));
// или
const newStr = /[^\d]*/.exec(str).pop();
// или
const newStr = [...str].reduceRight((acc, n) => '0123456789'.includes(n) ? '' : acc + n, '');
const sectionAttribute = element.getAttribute('data-content')
const titles = document.querySelectorAll('[data-title]');
const contents = document.querySelectorAll('[data-content]');
titles.forEach(n => n.addEventListener('click', onClick));
function onClick({ currentTarget: t }) {
titles.forEach(n => n.classList.toggle('active', n === t));
contents.forEach(n => n.hidden = n.dataset.content !== t.dataset.title);
}function toggle({ classList, dataset: { title } }, active) {
classList.toggle('active', active);
document.querySelector(`[data-content="${title}"]`)?.toggleAttribute('hidden', !active);
}
let active = document.querySelector('.active[data-title]');
document.addEventListener('click', ({ target: t }) =>
(t = t.closest('[data-title]')) &&
(active && toggle(active, false), toggle(active = t, true))
);
Object.values(arr.reduce((acc, { name, ...n }) => (
Object.values(n).find(Array.isArray)?.forEach(({ scores, channel }) =>
scores.forEach(({ score }) =>
(acc[channel]?.score > score) || (acc[channel] = { channel, name, score })
)
),
acc
), {}))
const payload = {
data: Object.fromEntries([
'раз свойство',
'два свойство',
'три свойство',
].map(n => [ n, this[n] ])),
};
new MutationObserver((mutations, observer) => {
if (mutations[0].target.classList.contains('интересующий-вас-класс')) {
observer.disconnect();
typed.start();
}
}).observe(элементНаличиеКлассаУКоторогоНадоОтследить, { attributes: true });
const getTheNearestLocation = (locations, [ x, y ]) =>
locations.reduce((nearest, n) => {
const d = ((n[1][0] - x) ** 2 + (n[1][1] - y) ** 2) ** 0.5;
return nearest[1] < d ? nearest : [ n, d ];
}, [ null, Infinity ])[0];
const parent = document.querySelector('ul');
const id = 'item';const elems = Array.from(parent.children);
const index = elems.findIndex(n => n.id === id);
const result = index === -1 ? elems : elems.slice(0, index);
// или
const result = [...parent.querySelectorAll(`:not(#${id}, #${id} ~ *)`)];
// или
const result = [];
for (
let el = parent.firstElementChild;
el && el.id !== id;
el = el.nextElementSibling
) {
result.push(el);
}
const result = arr
.map(Object.values)
.sort((a, b) => b - a)
.slice(0, 3)
.join(', ');map следовало бы использовать flatMap, но пока в элементах массива содержится по одному свойству - и так сойдёт.
const makeCensored = (str, words, replacement = '***') =>
str
.split(' ')
.map(n => words.includes(n) ? replacement : n)
.join(' ');
const result = Object.values(data.reduce((acc, { id, color }) => (
(acc[id] ??= { id, colors: [] }).colors.push(color),
acc
), {}));function group(data, key, val = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const getVal = val instanceof Function ? val : n => n[val];
const result = new Map;
for (const n of data) {
const k = getKey(n);
result.set(k, result.get(k) ?? []).get(k).push(getVal(n));
}
return result;
}const result = Array.from(
group(data, 'id', 'color'),
([ id, colors ]) => ({ id, colors })
);
str.split(';').pop()
// или
str.replace(/.*;/, '')
// или
str.match(/;(.*)/)[1]
// или
/[^;]+$/.exec(str).shift()
// или
str.slice(str.lastIndexOf(';') + 1)
// или
[...str].reduce((acc, n) => n === ';' ? '' : acc + n)
// или
Array.from(str).filter((n, i, a) => !a.includes(';', i)).join('')
const newArr = arr.map(function(n) {
return [ ...n, ...Array(this - n.length).fill('') ];
}, Math.max(...arr.map(n => n.length)));const max = arr.reduce((max, { length: n }) => max > n ? max : n, 0);
arr.forEach(n => n.push(...Array(max - n.length).fill('')));
parseInt('1!!!') // 1
+'1!!!' // NaN
parseInt('') // NaN
+'' // 0
parseInt('3.14159') // 3
+'3.14159' // 3.14159
parseInt('0b1000101') // 0
+'0b1000101' // 69
parseInt('0o273') // 0
+'0o273' // 187
parseInt({ valueOf: () => 666 }) // NaN
+({ valueOf: () => 666 }) // 666
parseInt('1000000000', 2) // 512
+'1000000000' // 1000000000
parseInt('99', 8) // NaN
+'99' // 99
parseInt('DEAD', 16) // 57005
+'DEAD' // NaN
parseInt(5067n) // 5067
+5067n // никакого числа тут не будет, получите TypeError
const target = document.querySelector('.color__des-item');
const container = document.querySelector('.color__list');
const key = 'name';
const attr = `data-${key}`;
const buttonSelector = `[${attr}]`;const getAttr = el => el.dataset[key];
// или
const getAttr = el => el.getAttribute(attr);
// или
const getAttr = el => el.attributes[attr].value;container.querySelectorAll(buttonSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => target.textContent = getAttr(e.currentTarget));container.addEventListener('click', ({ target: t }) =>
(t = t.closest(buttonSelector)) &&
(target.innerText = getAttr(t))
);
function update(target, source, key, props) {
source.forEach(function(n) {
const item = this[n[key]];
item && props.forEach(m => item[m] = n[m]);
}, Object.fromEntries(target.map(n => [ n[key], n ])));
}
update(directions, [ { раз объект }, { два объект }, ... ], 'id', [ 'color' ]);
function merge(key, ...arrs) {
const getKey = key instanceof Function ? key : n => n[key];
const result = new Map;
arrs.forEach(arr => arr.forEach(n => {
const k = getKey(n);
result.set(k, Object.assign(result.get(k) ?? {}, n));
}));
return [...result.values()];
}
const result = merge('id', testResult, test);function merge(key, target, ...arrs) {
const getKey = key instanceof Function ? key : n => n[key];
const targetMap = new Map(target.map(n => [ getKey(n), n ]));
arrs.forEach(arr => arr.forEach(n => {
const k = getKey(n);
targetMap.has(k) && Object.assign(targetMap.get(k), n);
}));
return target;
}
merge(n => n.id, testResult, test);