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',
});
const $checkbox = $('.form__chekbox');
const $cbAll = $checkbox.filter('.form__chekbox_all');
const $cb = $checkbox.not($cbAll);
$cbAll.change(e => $cb.prop('checked', false));
$cb.change(() => {
const $checked = $cb.filter(':checked');
const allChecked = $checked.length === $cb.length;
$cbAll.prop('checked', !$checked.length || allChecked);
$cb.prop('checked', (i, val) => allChecked ? false : val);
});
const combine = (keys, values, defaultValue = () => null) =>
Array.from(
{ length: Math.max(...values.map(n => n.length)) },
(_, i) => Object.fromEntries(keys.map((k, j) => [
k,
values[j][i] ?? defaultValue(i, j, k),
]))
);const keys = [ 'info', 'date' ];
// собираем элементы
const elements = combine(
keys,
keys.map(k => messagesData.querySelectorAll(`.${k}`)),
(i, j, k) => `элемент .${k} с индексом ${i} отсутствует`
);
// или, текстовое содержимое элементов
const texts = combine(
keys,
keys.map(k => Array.from(
messagesData.getElementsByClassName(k),
n => n.textContent
)),
);
new Date instanceof Object // true
/(?=.*1)(?=.*2)(?=.*3)/.test(str)[ 1, 2, 3 ].every(n => str.includes(n))new Set(str.match(/[123]/g)).size === 3
Как можно дополнить мой код, чтобы он проверял то, что требуется?
И можно как-нибудь без объявления переменной n внутри функции?
const getMaxDepth = arr =>
Array.isArray(arr)
? 1 + Math.max(0, ...arr.map(getMaxDepth))
: 0;console.log(getMaxDepth([ 1, [ 2 ], [ [ 3 ] ], [ [ [ 4 ] ] ] ])); // 4
console.log(getMaxDepth([])); // 1
console.log(getMaxDepth(666)); // 0
const createArr = (source, maxLength = source.length) =>
Array.from(
{ length: -~(Math.random() * maxLength) },
() => source[Math.random() * source.length | 0]
);const createArr = ([...source], maxLength = source.length) =>
Array.from(
{ length: Math.min(source.length, -~(Math.random() * maxLength)) },
() => source.splice(Math.random() * source.length | 0, 1)[0]
);function createArr([...source], maxLength = source.length) {
for (let i = source.length; --i > 0;) {
const j = Math.random() * -~i | 0;
[ source[j], source[i] ] = [ source[i], source[j] ];
}
return source.slice(0, -~(Math.random() * maxLength));
}
function createTable(
rows,
cols,
{
rowSeparator = '\n',
colSeparator = ' ',
} = {},
) {
const zeros = '0'.repeat(Math.ceil(Math.log10(rows * cols + 1)));
const result = [];
for (let i = 0; i < rows; i++) {
result.push(i ? rowSeparator : '');
for (let j = 0; j < cols; j++) {
result.push(
j ? colSeparator : '',
(zeros + (cols * i + j + 1)).slice(-zeros.length)
);
}
}
return ''.concat(...result);
}function createTable(
rows,
cols,
{
rowSeparator = '\n',
colSeparator = ' ',
} = {},
) {
const { length } = `${rows * cols}`;
return Array.from({ length: rows }, (_, i) =>
Array.from({ length: cols }, (_, j) =>
`${cols * i + j + 1}`.padStart(length, 0)
).join(colSeparator)
).join(rowSeparator);
}console.log(createTable(11, 9));
console.log(createTable(10, 10));
document.body.innerHTML = createTable(16, 16, {
rowSeparator: '<br>',
colSeparator: '____',
});
const SHOW_INITIAL = 3;
const SHOW_MORE = 5;
const listSelector = '.myList';
const itemSelector = 'li';
const showSelector = '.loadMore';
const hideSelector = '.showLess';
$(listSelector)
.on('click', showSelector, function({ delegateTarget: t }) {
$(`${itemSelector}:hidden`, t).slice(0, SHOW_MORE).show();
})
.on('click', hideSelector, function({ delegateTarget: t }) {
$(`${itemSelector}:visible`, t).slice(SHOW_INITIAL).slice(-SHOW_MORE).hide();
})
.each(function() {
$(itemSelector, this).slice(0, SHOW_INITIAL).show();
});
const sorted = (arr, path) => arr
.map(function(n) {
return [ n, this.reduce((p, c) => p?.[c], n) ];
}, path.split('.'))
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);const sorted = (arr, key) => arr
.map(n => [ n, key(n) ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);const sortedByCommentsCount = sorted(arr, n => n.comments.count);
const sortedByLengthDesc = sorted(arr, n => -n.length);
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
const data = Object.fromEntries(new FormData(this));
console.log(JSON.stringify(data, null, 2));
});
const pickers = $('селектор элементов, на которых инициализируются экземпляры календаря')
.datepicker({
onSelect(formattedDate, date, picker) {
pickers.forEach(n => n !== picker && (
n.currentDate = picker.currentDate,
n.selectedDates = [ date ],
n.update()
));
},
})
.get()
.map(n => $(n).data('datepicker'));const options = {
onSelect({ date, datepicker }) {
pickers.forEach(n => n !== datepicker && n.update({
viewDate: datepicker.viewDate,
selectedDates: [ date ],
}, {
silent: true,
}));
},
};
const pickers = Array.from(
document.querySelectorAll('селектор элементов с календарями'),
n => new AirDatepicker(n, options)
);
<select id="country"></select>
<select id="city"></select>const setOptions = (el, data) =>
el.innerHTML = data
.map(n => `<option>${n}</option>`)
.join('');
const countries = [
{ name: 'Германия', cities: [ 'Берлин', 'Бонн', 'Мюнхен' ] },
{ name: 'Франция', cities: [ 'Париж', 'Лион', 'Марсель' ] },
{ name: 'Италия', cities: [ 'Рим', 'Неаполь', 'Милан' ] },
];
const country = document.querySelector('#country');
const city = document.querySelector('#city');
setOptions(country, countries.map(n => n.name));
country.addEventListener('change', function() {
setOptions(city, countries.find(n => n.name === this.value).cities);
});
country.dispatchEvent(new Event('change'));
const sortedInventory = Object
.values(inventory)
.sort((a, b) => a.price - b.price)
.map(n => `${n.title} - ${n.amount}`)
.join('\n');
const add = (str, val) =>
str.replace(/\d+$/, m => `${+m + val}`.padStart(m.length, 0));add('string0001', 1) // 'string0002'
add('string1010', 99) // 'string1109'
add('string2345', 6789) // 'string9134'string99 + 1 должно быть равно string00, а не string100), то после вызова padStart добавьте .slice(-m.length).
<p class="typeit">hello, world!!</p>
<p class="typeit">fuck the world</p>
<p class="typeit">fuck everything</p>const typeit = Array.from(
document.querySelectorAll('.typeit'),
(n, i) => new TypeIt(n, {
cursor: false,
afterComplete: () => typeit[i + 1]?.go(),
})
);
typeit[0].go();