const getPrimitives = data =>
data instanceof Object
? Object.values(data).flatMap(getPrimitives)
: [ data ];
function getPrimitives(data) {
const result = [];
const stack = [];
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 Object) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, Object.values(arr[i]) ];
} else {
result.push(arr[i]);
}
}
return result;
}
// или
function getPrimitives(data) {
const result = [];
for (const stack = [ data ]; stack.length;) {
const n = stack.pop();
if (n instanceof Object) {
stack.push(...Object.values(n).reverse());
} else {
result.push(n);
}
}
return result;
}
// или
function getPrimitives(data) {
const result = [].concat(data);
for (let i = 0; i < result.length; i++) {
const n = result[i];
if (n instanceof Object) {
result.splice(i--, 1, ...Object.values(n));
}
}
return result;
}
const data = Array
.from(document.querySelectorAll('.input-container'))
.reduce((acc, el, i) => (
acc[`input${i + 1}`] = [
'parameter',
'result',
'select',
'range',
].map(name => el.querySelector(`[name="${name}"]`).value),
acc
), {});
<div class="colorsSelector">
<div class="colorItem" data-color="blue"></div>
<div class="colorItem" data-color="white"></div>
<div class="colorItem" data-color="red"></div>
<div class="colorItem" data-color="black"></div>
<div class="colorItem" data-color="white-pure"></div>
<div class="colorItem" data-color="orange"></div>
<div class="colorItem" data-color="graphite"></div>
</div>
[data-color="blue"] { background-color: #325488; }
[data-color="white"] { background-color: #cfcfcf; }
[data-color="red"] { background-color: #c64040; }
[data-color="black"] { background-color: #08090b; }
[data-color="white-pure"] { background-color: #f0f0f0; }
[data-color="orange"] { background-color: #d87c5a; }
[data-color="graphite"] { background-color: #7f7f7f; }
const container = document.querySelector('.colorsSelector');
const itemSelector = '.colorItem';
const activeClass = 'colorItem--active';
const img = document.querySelector('.imgHolder img');
const src = color => `//webcademy.ru/files/js2020/solaris/${color}.png`;
// делегированный обработчик клика назначается контейнеру с цветами
container.addEventListener('click', ({ target: { dataset: { color } } }) => {
if (color) {
img.src = src(color);
document.querySelectorAll(itemSelector).forEach(n => {
n.classList.toggle(activeClass, color === n.dataset.color);
});
}
});
// или, каждому цвету обработчик клика назначается индивидуально
const items = container.querySelectorAll(itemSelector);
items.forEach(n => n.addEventListener('click', onClick));
function onClick({ target: t }) {
img.src = src(t.dataset.color);
items.forEach(n => n.classList.toggle(activeClass, n === t));
}
const url = new URL('https://qna.habr.com/?test=123&frukt=yabloko');
console.log(url.searchParams.get('test'));
const str = 'https://qna.habr.com/?test=123&frukt=yabloko';
const usp = new URLSearchParams(str.replace(/^[^?]*\?/, '')); // или str.split('?').pop()
console.log(usp.get('test'));
[ 5, 8, 10 ].forEach((n, i, a) => $items.slice(a[i - 1], n).wrapAll('<div>'));
const arr = Object
.entries(obj)
.reduce((acc, [ k, values ]) => (
values.forEach((v, i) => (acc[i] ??= {})[k] = v),
acc
), []);
const keys = Object.keys(obj);
const arr = obj[keys[0]]?.map((_, i) => {
return Object.fromEntries(keys.map(k => [ k, obj[k][i] ]));
}) ?? [];
const duplicates = arr.filter((n, i, a) => a.filter(m => m[0] === n[0]).length > 1);
const duplicates = Object
.values(arr.reduce((acc, n) => ((acc[n[0]] ??= []).push(n), acc), {}))
.flatMap(n => n.length > 1 ? n : []);
const duplicates = Array
.from(arr
.reduce((acc, n) => (acc.get(n[0]).push(n), acc), new Map(arr.map(n => [ n[0], [] ])))
.values())
.reduce((acc, n) => (n.length > 1 && acc.push(...n), acc), []);
const duplicates = arr.filter(function(n) {
return this.get(n[0]);
}, arr.reduce((acc, [ n ]) => acc.set(n, acc.has(n)), new Map));
document.querySelector('.btn--start').addEventListener('click', filterItems);
document.querySelector('select').addEventListener('change', e => e.target.value === 'all' && filterItems());
function filterItems() {
const val = document.querySelector('select').value;
document.querySelectorAll('.item').forEach(n => {
n.style.display = [ n.dataset.elem, 'all' ].includes(val)
? 'block'
: 'none';
});
}
Object.fromEntries(new URLSearchParams(arr.join('&')))
arr.reduce((acc, n) => (
n = n.split('='),
acc[n[0]] = n[1],
acc
), {})
Object.assign(...arr.map(n => n.match(/[^=]+/g)).map(([ k, v ]) => ({ [k]: v })))
eval(`({${arr.map(n => `"${n.replace('=', '":"')}"`)}})`)
<div data-value="69"></div>
<div data-value="187"></div>
<div data-value="666"></div>
function animateValue(elem) {
return new Promise(resolve => {
const endValue = +elem.dataset.value;
let currValue = 0;
const interval = setInterval(() => {
if (++currValue === endValue) {
clearInterval(interval);
resolve();
}
elem.innerText = currValue;
}, 20);
});
}
Array
.from(document.querySelectorAll('[data-value]'))
.reduce((p, c) => p.then(() => animateValue(c)), Promise.resolve());
const result = arr.reduce((acc, n, i) => (
(i & 1) || acc.push(0),
acc[~-acc.length] += n,
acc
), []);
function chunked(data, chunkSize) {
return Array.prototype.reduce.call(
data,
(acc, n, i) => ((acc[i / chunkSize | 0] ??= []).push(n), acc),
[]
);
}
function sum(data, val = n => n) {
const getVal = val instanceof Function ? val : n => n[val];
return Array.prototype.reduce.call(
data,
(acc, n) => acc + getVal(n),
0
);
}
const result = chunked(arr, 2).map(n => sum(n));
.active {
&::after {
content: "hello, world!!";
}
}
<a class="tabs-select__button" data-text="hello, world!!">
<a class="tabs-select__button" data-text="fuck the world">
.active {
&::after {
content: attr(data-text);
}
}
const flatArr = arr.flatMap(n => Array.isArray(n.DOP) ? n.DOP : []);
// или
const flatArr = Array.prototype.concat.apply([], arr.map(n => n.DOP ?? []));
// или
const flatArr = arr.reduce((acc, n) => (n.DOP && acc.push(...n.DOP), acc), []);
const unique = Object.values(Object.fromEntries(flatArr.map(n => [ n.NAME, n ])));
// или
const unique = flatArr.filter(function({ NAME: n }) {
return !(this[n] = this.hasOwnProperty(n));
}, {});
// или
const unique = flatArr.filter((n, i, a) => n === a.find(m => m.NAME === n.NAME));
function formatDate(str) {
const d = new Date(str.replace('_', ' 1, '));
d.setMonth(d.getMonth() - 1);
return d.toLocaleDateString('en-US', {
month: 'short',
year: 'numeric',
}).replace(' ', '_');
}
formatDate('Feb_2021') // "Jan_2021"
formatDate('Jan_2000') // "Dec_1999"
str.match(/(?<=\. ).+(?= \(%\))/)[0]
// или
str.replace(/^.*?\. | \(%\).*$/g, '')
// или
str.split('. ').pop().split(' (%)').shift()