const insert = (str, indices, substr = ' ') =>
Array.prototype.reduce.call(
str,
(acc, n, i) => acc + (indices.includes(i) ? substr : '') + n,
''
);
// или
const insert = (str, indices, substr = ' ') => [...indices]
.sort((a, b) => b - a)
.reduce((acc, n) => (acc.splice(n, 0, substr), acc), [...str])
.join('');
// или
const insert = (str, indices, substr = ' ') => []
.concat(0, indices)
.sort((a, b) => a - b)
.map((n, i, a) => str.slice(n, a[i + 1]))
.join(substr);
// или
const insert = (str, indices, substr = ' ') => indices.length
? str.replace(RegExp(indices.map((n, i) => `(?<=^.{${n}})`).join('|'), 'g'), substr)
: str;
str = insert(str, [ 1, 3, 6, 8, 10 ]);
. $(window).on('scroll', function() {
const top = $(this).scrollTop();
const index = [ 50, 100, 150, Infinity ].findIndex(n => n > top);
$('.int > div').removeClass('active').eq(index).addClass('active');
}).scroll();
не могу понять, как сделать так, чтобы при втором условии числа выводились от меньшего к большему
const step = Math.sign(p2 - p1);
while (Math.abs(p2 - p1) >= 1) {
p1 += step;
console.log(p1);
}
[ p1, p2 ] = p1 > p2 ? [ p2, p1 ] : [ p1, p2 ];
while (p1 < p2) {
p1 += 1;
console.log(p1);
}
const
[ name, price, number ] =
[ 'name', 'price', 'number' ]
.map(n => document.querySelector(`input[name="${n}"]`).value.split(', '));
const arr = name.map((n, i) => ({
name: n,
price: price[i],
number: +number[i],
}));
numberInput.addEventListener('input', ({ target: t }) => {
t.value = ((t.value.match(/\d/g) || []).join('').match(/\d{1,4}/g) || []).join(' ');
});
const { position, cell_radius, food_size, food } = this;
const isIntersects = (a, b) =>
(a.x - b.x) ** 2 + (a.y - b.y) ** 2 <= (cell_radius + food_size) ** 2;
food.reduceRight((_, n, i, a) => isIntersects(n, position) && a.splice(i, 1), null);
// или
food.splice(0, food.length, ...food.filter(n => !isIntersects(n, position)));
// или
food.length -= food.reduce((acc, n, i, a) => (
a[i - acc] = n,
acc + isIntersects(n, position)
), 0);
const index = str.search(/\d/);
.const index = str.match(/^(\D*\d)?/)[0].length - 1;
// или
const index = [...str].findIndex(n => !Number.isNaN(Number(n)));
// или
let index = -1;
for (let i = 0; i < str.length; i++) {
if ('0123456789'.includes(str.charAt(i))) {
index = i;
break;
}
}
// или
const index = (function get(i, n = str[i]) {
return (
!n ? -1 :
+n === +n ? i :
get(-~i)
);
})(0);
При движении вверх или влево координаты искажаются.
$('селектор картинок').unwrap();
function unwrap(element) {
const wrapper = element.parentNode;
const fragment = new DocumentFragment();
DocumentFragment.prototype.append.apply(fragment, wrapper.childNodes);
wrapper.parentNode.replaceChild(fragment, wrapper);
}
// или
const unwrap = ({ parentNode: wrapper }) =>
wrapper.replaceWith(...wrapper.childNodes);
document.querySelectorAll('селектор картинок').forEach(unwrap);
const newArr = arr.map((n, i) => n.repeat(i + 1));
const newArr = arr.map((n, i) => Array(i + 1).fill(n).join(''));
const newArr = arr.map((n, i) => Array(i + 2).join(n));
const newArr = [];
for (let i = 0; i < arr.length; i++) {
let str = '';
for (let j = 0; j <= i; j++) {
str += arr[i];
}
newArr.push(str);
}
const newArr = [];
for (const n of arr) {
let str = '';
while ((str = str.concat(n)).length <= newArr.length) ;
newArr[newArr.length] = str;
}
const select = document.querySelector('[name="auto_model"]');
select.append(...Object.values([...select].reduce((acc, n) => {
if (n.value) {
const k = n.dataset.mark;
acc[k] || ((acc[k] = document.createElement('optgroup')).label = k);
acc[k].append(n);
}
return acc;
}, {})));
/\w{6}/.test(password)
At least six characters long
^
- начало строки, $
- конец); символов может быть больше шести (квантификатор {}
позволяет указывать диапазон значений, верхнюю границу оставляем открытой). Т.е., правильно будет так:/^\w{6,}$/.test(password)
\w
- не alphanumeric, это ещё и _
, так что придётся перечислить нужные символы в более явном виде. Кроме того, вместо четырёх отдельных выражений можно сделать одно:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$/.test(password)
document.querySelector('button').addEventListener('click', function() {
const val = +document.querySelector('#elem1').value;
const sign = Math.sign(val);
document.querySelector('#str').innerHTML = Array
.from({ length: val * sign + 1 }, (n, i) => val - i * sign)
.join('<br>');
});
$('.nextArrow, .backArrow').on('animationend', e => e.target.style.animation = '');
function openCity(e, city) {
document.querySelectorAll('.tablink').forEach(n => {
n.classList.toggle('active', city === 'All' || n === e.target);
});
document.querySelectorAll('.tabcontent').forEach(n => {
n.style.display = city === 'All' || n.id === city ? 'block' : 'none';
});
}