const markersData = [
{ position: { lat: ..., lng: ... }, content: '...' },
{ position: { lat: ..., lng: ... }, content: '...' },
...
];const infoWindow = new google.maps.InfoWindow();const markers = markersData.map(({ position, content }) => {
const marker = new google.maps.Marker({ position, map });
marker.addListener('click', () => {
infoWindow.setContent(content);
infoWindow.open(map, marker);
});
return marker;
});null):const setActiveIcon = marker => markers.forEach(n => n.setIcon(n === marker ? iconActive : icon));
function createTree({
data,
key = 'id',
childrenKeysKey = 'children',
childrenKey = 'children',
}) {
const tree = Object.fromEntries(data.map(({ [childrenKeysKey]: _, ...n }) => [ n[key], n ]));
data.forEach(n => tree[n[key]][childrenKey] = n[childrenKeysKey]?.map?.(m => tree[m]) ?? []);
const nonRootIds = new Set(data.flatMap(n => n[childrenKeysKey] ?? []));
return Object.values(tree).filter(n => !nonRootIds.has(n[key]));
}const tree = createTree({
data,
childrenKeysKey: 'parts',
});
<div class="wrapper">.const containerSelector = '.wrapper';
const headerSelector = '.request__nav__item';
const contentSelector = '.request__field';
const activeClass = 'active';
$(containerSelector).on('click', headerSelector, function(e) {
const $headers = $(headerSelector, e.delegateTarget);
const index = $headers.index(this);
$headers.removeClass(activeClass).eq(index).addClass(activeClass);
$(contentSelector, e.delegateTarget).hide().eq(index).fadeIn();
}).each(function() {
$(headerSelector, this).first().click();
});
$('a').click(function() {
const $tabs = $('.splCont');
const $tab = $tabs.eq($(this).index()).toggle('normal');
$tabs.not($tab).hide('normal');
return false;
});
const toSeconds = str => str
.split(':')
.reverse()
.reduce((acc, n, i) => acc + n * (60 ** i), 0);
const sumDiagonals = matrix =>
matrix.reduce((acc, n, i) => {
acc.principal += n[i];
acc.secondary += n[n.length - i - 1];
return acc;
}, {
principal: 0,
secondary: 0,
});
const result = [];
for (const n of numbers) {
if (!objects.some(m => m.number === n)) {
result.push(n);
}
}const result = [];
COLLECT_NUMBERS:
for (let i = 0; i < numbers.length; i++) {
for (let j = 0; j < objects.length; j++) {
if (objects[j].number === numbers[i]) {
continue COLLECT_NUMBERS;
}
}
result[result.length] = numbers[i];
}const result = numbers.filter(function(n) {
return !this.has(n);
}, new Set(objects.map(n => n.number)));const result = (function get(exclude, i, n = numbers[--i]) {
return i >= 0
? get(exclude, i).concat(~exclude.indexOf(n) ? [] : n)
: [];
})(objects.map(n => n.number), numbers.length);const result = [...objects.reduce(
(acc, n) => (acc.delete(n.number), acc),
new Set(numbers)
)];
const newArr = [...arr]
.sort((a, b) => a.name.localeCompare(b.name) || (a.price - b.price))
.filter((n, i, a) => n.name === a[i - 1]?.name);const newArr = [...arr]
.sort((a, b) => a.name.localeCompare(b.name) || (a.price - b.price))
.filter((n, i, a) => n.name === a[~-i]?.name || n.name !== a[-~i]?.name);const newArr = [...arr]
.sort((a, b) => a.price - b.price)
.filter((n, i, a) => n !== a.find(m => m.name === n.name));const newArr = [...arr].sort((a, b) => a.price - b.price);
Object
.values(newArr.reduce((acc, n) => ((acc[n.name] ??= []).push(n), acc), {}))
.forEach(n => n.length !== 1 && newArr.splice(newArr.indexOf(n[0]), 1));
const values = Object.values(obj);
const min = Math.min(...values);
const max = Math.max(...values);const [ min, max ] = Object
.values(obj)
.reduce(([ min, max ], n) => [
n < min ? n : min,
n > max ? n : max,
], [ Infinity, -Infinity ]);let min = Infinity;
let max = -Infinity;
for (const k in obj) {
if (obj.hasOwnProperty(k)) {
const v = obj[k];
(min > v) && (min = v);
(max < v) && (max = v);
}
}
const mustStay = n => n !== null;.const newArr = arr.map(n => ({
...n,
array2: n.array2.filter(mustStay),
}));for (let i = 0; i < arr.length; i++) {
const a = arr[i].array2;
for (let j = 0; j < a.length; j++) {
if (!mustStay(a[j])) {
for (let k = j--; ++k < a.length; a[k - 1] = a[k]) ;
a.pop();
}
}
}
// или
arr.forEach(n => {
n.array2.reduceRight((_, n, i, a) => mustStay(n) || a.splice(i, 1), 0);
});
// или
(function next(i, { array2: a } = arr[i] ?? {}) {
if (a) {
a.splice(0, a.length, ...a.filter(mustStay));
next(-~i);
}
})(0);
// или
for (const { array2: a } of arr) {
a.length -= a.reduce((acc, n, i) => (
a[i - acc] = n,
acc + !mustStay(n)
), 0);
}
const table = document.querySelector('table');
const columnIndex = Object.fromEntries(Array.from(
table.tHead.rows[0].cells,
n => [ n.innerText.toLowerCase(), n.cellIndex ]
));
function onChange() {
const filters = Object.entries(Array.prototype.reduce.call(
document.querySelectorAll('.list-group :checked'),
(acc, n) => ((acc[columnIndex[n.name]] ??= []).push(n.value), acc),
{}
));
for (const { rows } of table.tBodies) {
for (const tr of rows) {
tr.hidden = filters.some(n => !n[1].includes(tr.cells[n[0]].innerText));
}
}
}
document.querySelectorAll('.list-group').forEach(n => {
n.addEventListener('change', onChange);
});
const getElementsWithDepth = (el, depth = 0) =>
[...el.children].reduce((acc, n) => (
acc.push(...getElementsWithDepth(n, depth + 1)),
acc
), [ { el, depth } ]);function getElementsWithDepth(root) {
const result = [];
for (const stack = [ [ root, 0 ] ]; stack.length;) {
const [ el, depth ] = stack.pop();
result.push({ el, depth });
stack.push(...Array.from(el.children, n => [ n, -~depth ]).reverse());
}
return result;
}
// или
const getElementsWithDepth = root =>
Array.prototype.reduce.call(
root.querySelectorAll('*'),
(acc, n) => {
acc.push({ el: n, depth: 1 });
for (; (n = n.parentNode) !== root; acc[acc.length - 1].depth++) ;
return acc;
},
[ { el: root, depth: 0 } ]
);
function getDays(year, month) {
const days = [];
const d = new Date(year, month, 1);
let week = 1;
while (d.getMonth() === month) {
const date = d.getDate();
const day = d.getDay();
days.push({
day: date,
weeknumber: (day === 1 || date === 1) ? week : false,
weekday: d.toLocaleString('en-US', { weekday: 'short' }),
});
d.setDate(date + 1);
week += !day;
}
return days;
}
const count = text.match(RegExp(str, 'g'))?.length ?? 0;
// или
const count = text.split(str).length - 1;
// или
const count = (function get(pos) {
const i = text.indexOf(str, pos);
return +(i !== -1) && -~get(i + str.length);
})(0);
const isObject = v =>
v instanceof Object && !Array.isArray(v);const flatObj = obj => Object
.entries(isObject(obj) ? obj : {})
.reduce((acc, [ k, v ]) => (
isObject(v)
? Object.assign(acc, flatObj(v))
: acc[k] = v,
acc
), {});function flatObj(obj) {
const result = {};
for (const stack = isObject(obj) ? [ [ , obj ] ] : []; stack.length;) {
const [ k, v ] = stack.pop();
if (isObject(v)) {
stack.push(...Object.entries(v).reverse());
} else {
result[k] = v;
}
}
return result;
}
document.querySelectorAll('h2').forEach(n => {
const [ season, , episode ] = n.innerText.split(' ');
if (+episode === 1) {
n.id = `season-${season}`;
}
});[...document.querySelectorAll('h2')]
.filter(n => n.innerText.endsWith(', 1 серия'))
.forEach((n, i) => n.id = `season-${i + 1}`);document.querySelectorAll('h2').forEach((n, i, a) => {
const prev = i && a[i - 1].innerText.match(/\d+/)[0];
const curr = n.innerText.match(/\d+/)[0];
if (curr !== prev) {
n.id = `season-${curr}`;
}
});Array
.from(document.querySelectorAll('h2'))
.reduce((acc, n) => (acc[parseInt(n.innerText)] ??= n, acc), [])
.forEach((n, i) => n.id = `season-${i}`);
const transpose = matrix => Array.from(
{ length: matrix[0]?.length ?? 0 },
(_, i) => matrix.map(n => n[i])
);function transpose(matrix) {
const result = Array(matrix.length && matrix[0].length);
for (let i = 0; i < result.length; i++) {
result[i] = [];
for (let j = 0; j < matrix.length; j++) {
result[i][j] = matrix[j][i];
}
}
return result;
}
const result = arr.reduce((acc, n, i, a) => (
n === a[i - 1] + 1 || acc.push([]),
acc[acc.length - 1].push(n),
acc
), []);function groupAdjacent(
data,
{
key = n => n,
newGroup = (c, p) => c !== p,
} = {}
) {
const getVal = key instanceof Function ? key : n => n[key];
return Array.prototype.reduce.call(
data,
(acc, n, i) => {
const v = getVal(n, i);
const iGroup = acc[0].length - (i && !newGroup(v, acc[1]));
(acc[0][iGroup] ??= []).push(n);
acc[1] = v;
return acc;
},
[ [], null ]
)[0];
}const result = groupAdjacent(arr, { newGroup: (c, p) => c !== -~p });
// или
const result = groupAdjacent(arr, { key: (n, i) => n - i });
$('.js-cropped-word').text((i, text) => text.replace(/(?<=\S{19,}).+/, '...'));В Сафари не работает
document.querySelectorAll('.js-cropped-word').forEach(n => {
n.textContent = n.textContent.replace(/(\S{19}).+/, '$1...');
});const max = 19;
for (const n of document.getElementsByClassName('js-cropped-word')) {
const words = n.innerText.split(' ');
const i = words.findIndex(n => n.length > max);
if (i !== -1) {
words.length = i + 1;
words[i] = words[i].slice(0, max) + '...';
n.innerText = words.join(' ');
}
}