const result = arrs.reduce(
(acc, arr) => (arr.forEach((n, i) => acc[i].push(...n.slice(acc[i].length))), acc),
Array.from({ length: Math.max(...arrs.map(arr => arr.length)) }, () => [])
);
const result = arrs.reduce((acc, arr) => (
arr.forEach((n, i) => (
acc[i] = acc[i] || [],
n.forEach((m, j) => acc[i][j] = acc[i][j] || m)
)),
acc
), []);
Метод Performance.now()
возращает временную метку DOMHighResTimeStamp, измеряемую в миллисекундах
const createArr = (len, digit, count) => {
const d = [...Array(9)].map((n, i) => i + (i >= digit));
return [...Array(len)].map(() => {
const number = [...Array(Math.random() * 10 | 0)].map(() => d[Math.random() * d.length | 0]);
for (let i = 0; i < count; i++) {
number.splice(Math.random() * number.length | 0, 0, digit);
}
return +number.join('');
});
};
const arr = createArr(5, 1, 2);
const tbody = document.querySelector('#test tbody');
const keys = [ 'name.firstName', 'name.lastName', 'about', 'eyeColor' ].map(n => n.split('.'));
const getVal = (obj, keys) => keys.reduce((p, c) => p != null ? p[c] : p, obj);
for (const n of data) {
keys.forEach(function(k) {
this.insertCell().textContent = getVal(n, k);
}, tbody.insertRow());
}
// или
tbody.insertAdjacentHTML('beforeend', data
.map(n => `
<tr>${keys.map(k => `
<td>${getVal(n, k)}</td>`).join('')}
</tr>`)
.join('')
);
AutoNumeric.multiple('.numeric', {
decimalCharacter : '.',
digitGroupSeparator : ' ',
})
<div id="images">
<img src="https://placehold.co/200x200/FF0000/FFFFFF/png">
<img src="https://placehold.co/200x200/00FF00/000000/png">
<img src="https://placehold.co/200x200/0000FF/FFFFFF/png">
</div>
#images img {
transition: transform 0.7s;
}
.rotate {
transform: rotateY(180deg);
}
const toggleRotate = el => el.classList.toggle('rotate');
document.querySelectorAll('#images img').forEach((n, i) => {
setTimeout(setInterval, 300 * i, toggleRotate, 2000, n);
});
#images img {
animation: rotate 4s infinite;
}
#images img:nth-child(1) { animation-delay: 0s; }
#images img:nth-child(2) { animation-delay: 0.3s; }
#images img:nth-child(3) { animation-delay: 0.6s; }
@keyframes rotate {
0%, 75%, 100% {
transform: rotateY(0deg);
}
25%, 50% {
transform: rotateY(180deg);
}
}
messages.sort((a, b) => {
[ a, b ] = [ a, b ].map(n => sortableLanguages.indexOf(n.language));
return a === -1 ? 1 : b === -1 ? -1 : a - b;
});
const sorted = (arr, key) => arr
.map(n => [ n, key(n) ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);
const order = Object.fromEntries(sortableLanguages.map((n, i) => [ n, i + 1 ]));
const sortedMessages = sorted(messages, n => order[n.language] || Number.MAX_SAFE_INTEGER);
// или
function sorted(arr, order, key) {
const ordered = new Map(order.map(n => [ n, [] ]));
const unordered = [];
arr.forEach(n => (ordered.get(key(n)) || unordered).push(n));
return [].concat(...ordered.values(), unordered);
}
const sortedMessages = sorted(messages, sortableLanguages, n => n.language);
const buttonSelector = '.one';
const contentSelector = '.two';
const className = 'three';
document.querySelector(buttonSelector).addEventListener('click', () => {
document.querySelector(contentSelector).classList.toggle(className);
});
document.addEventListener('click', e => {
const button = e.target.closest(buttonSelector);
if (button) {
const index = [...document.querySelectorAll(buttonSelector)].indexOf(button);
document.querySelectorAll(contentSelector)[index].classList.toggle(className);
}
});
// или
const buttons = document.querySelectorAll(buttonSelector);
const contents = document.querySelectorAll(contentSelector);
buttons.forEach(n => n.addEventListener('click', onClick));
function onClick(e) {
const index = Array.prototype.indexOf.call(buttons, e.currentTarget);
contents[index].classList.toggle(className);
}
for (let i = 0; i < password.length; i + 1) {
если запустить код то страница крашнется, codesandbox на счет этого говорит что циклов слишком много
i + 1
- счётчик не меняет своего значения, цикл получается бесконечным.i += 1
или i++
.return pass;
return text
. const mustStay = arr => arr.some(n => n !== '');
const newArr = arr.filter(mustStay);
arr.reduceRight((_, n, i, a) => mustStay(n) || a.splice(i, 1), null);
// или
arr.splice(0, arr.length, ...arr.filter(mustStay));
// или
let numDeleted = 0;
for (const [ i, n ] of arr.entries()) {
arr[i - numDeleted] = n;
numDeleted += !mustStay(n);
}
arr.length -= numDeleted;
[...divs.keys()].forEach(i => console.log(i));
// или
console.log(Array.from(divs.keys(), i => i * 100));
// или
for (const i of divs.keys()) {
console.log(i);
}
const attrName = 'data-i';
const attrValues = [ 'qwe', 'asd', 'zxc' ];
const className = 'класс';
document
.querySelectorAll(attrValues.map(n => `[${attrName}="${n}"]`))
.forEach(n => n.classList.add(className));
document.querySelectorAll(`[${attrName}]`).forEach(n => {
n.classList.toggle(className, attrValues.includes(n.getAttribute(attrName)));
});
на JS...
document.querySelectorAll('.scroll_list li').forEach(n => {
n.innerHTML = n.textContent.replace(/\d+ шт./, '<span>$&</span>');
});
// или
for (const n of document.querySelector('.scroll_list').children) {
n.innerHTML = n.innerText.replace(/\S+ \S+$/, m => `<span>${m}</span>`);
}
...или PHP
span
создавался сразу. <p>
<b>Text</b>
<input type="text" id="text">
<b>Color</b>
<input type="text" id="color">
</p>
<button id="create">create</button>
<button id="update">update</button>
<button id="del">delete</button>
<ul id="items"></ul>
.active {
border: 2px solid black;
}
const
[ items, text, color, create, update, del ] =
[ 'items', 'text', 'color', 'create', 'update', 'del' ]
.map(n => document.getElementById(n));
create.addEventListener('click', () => {
items.insertAdjacentHTML('beforeend', `<li style="color: ${color.value}">${text.value}</li>`);
updateForm('', '');
});
update.addEventListener('click', () => ifActive(a => {
a.innerText = text.value;
a.style.color = color.value;
}));
del.addEventListener('click', () => ifActive(a => a.remove()));
items.addEventListener('click', e => {
const item = e.target.closest('li');
if (item) {
ifActive(a => item !== a && a.classList.remove('active'));
item.classList.toggle('active');
ifActive(a => updateForm(a.innerText, a.style.color));
}
});
function ifActive(f) {
const active = items.querySelector('.active');
active && f(active);
}
function updateForm(textVal, colorVal) {
text.value = textVal;
color.value = colorVal;
}
nums1 = nums1.slice(0, m).concat(nums2).sort((a, b) => a - b);
nums1.splice(0, nums1.length, ...[ ...nums1.slice(0, m), ...nums2 ].sort((a, b) => a - b));
// или
nums1.slice(0, m).concat(nums2).sort((a, b) => a - b).forEach((n, i) => nums1[i] = n);
const ceil = (value, precision) => Math.ceil(value / precision) * precision;
const values = [ 1, 2, 3, 163, 200.001, 99.999 ];
values.map(n => ceil(n, 1)); // [ 1, 2, 3, 163, 201, 100 ]
values.map(n => ceil(n, 10)); // [ 10, 10, 10, 170, 210, 100 ]
values.map(n => ceil(n, 5)); // [ 5, 5, 5, 165, 205, 100 ]
<div class="angle">
<div class="angle-input">
<div class="angle-input-arrow"></div>
</div>
<input type="number" min="0" max="360" value="0">
</div>
.angle {
display: inline-flex;
align-items: center;
border: 1px solid silver;
padding: 5px;
}
.angle-input {
display: inline-flex;
justify-content: center;
border: 1px solid black;
border-radius: 50%;
width: 50px;
height: 50px;
margin-right: 10px;
}
.angle-input-arrow {
height: 50%;
border: 1px solid black;
transform-origin: 50% 100%;
box-sizing: border-box;
pointer-events: none;
}
document.querySelector('.angle input').addEventListener('input', function(e) {
const arrow = this.closest('.angle').querySelector('.angle-input-arrow');
arrow.style.transform = `rotate(${e.target.value}deg)`;
});
const angleInput = document.querySelector('.angle-input');
angleInput.addEventListener('mousedown', onAngleInput);
angleInput.addEventListener('mousemove', onAngleInput);
function onAngleInput(e) {
if (e.buttons === 1) {
const {
offsetX: x, offsetY: y,
target: t,
target: { offsetWidth: w, offsetHeight: h }
} = e;
const deg = (450 + (Math.atan2(y - h / 2, x - w / 2) * (180 / Math.PI) | 0)) % 360;
t.querySelector('.angle-input-arrow').style = `transform: rotate(${deg}deg)`;
t.closest('.angle').querySelector('input').value = deg;
}
}