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 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);
new Date(str.split(' ', 1)[0].split('.').reverse().join('-')).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);
});
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) =>
[...Array(1 + Math.random() * maxLength | 0)].map(() => source[Math.random() * source.length | 0]);
const [ arr1, arr2, arr3 ] = [...Array(3)].map(() => createArr(arr, 5));
const createArr = ([...source], maxLength) => Array.from(
{ length: Math.min(source.length, 1 + Math.random() * maxLength | 0) },
() => source.splice(Math.random() * source.length | 0, 1)[0]
);
function createArr(source, maxLength) {
const arr = source.slice();
for (let i = arr.length; --i > 0;) {
const j = Math.random() * (i + 1) | 0;
[ arr[j], arr[i] ] = [ arr[i], arr[j] ];
}
return arr.slice(0, 1 + Math.random() * maxLength | 0);
}
function createTable(rows, cols) {
const maxLen = `${rows * cols}`.length;
return [...Array(rows)]
.map((n, i) => [...Array(cols)]
.map((m, j) => `${cols * i + j + 1}`.padStart(maxLen, 0))
.join(' '))
.join('\n');
}
function createTable(rows, cols) {
const zeroStr = Array(1 + Math.ceil(Math.log10(rows * cols + 1))).join(0);
let result = '';
for (let i = 0; i < rows; i++) {
result += i ? '\n' : '';
for (let j = 0; j < cols; j++) {
result += (j ? ' ' : '') + (zeroStr + (cols * i + j + 1)).slice(-zeroStr.length);
}
}
return result;
}
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));
});