function createList(data) {
const list = document.createElement('ul');
const stack = [];
let [ ul, level ] = [ list, +/\d+/.exec(data[0]) ];
for (const n of data) {
const currLevel = +/\d+/.exec(n);
if (currLevel > level) {
stack.push([ ul, level ]);
[ ul, level ] = [ document.createElement('ul'), currLevel ];
stack[stack.length - 1][0].lastChild.append(ul);
} else {
for (; currLevel !== level; [ ul, level ] = stack.pop()) ;
}
ul.append(document.createElement('li'));
ul.lastChild.textContent = n;
}
return list;
}
изучаю метод фильтр
greater than or equal to 8.0
rating > 8
combination of filter and map
watchList.filter(n => n.imdbRating >= 8).map(n => ({ title: n.Title, rating: n.imdbRating }))
.one path {
fill: #909090;
}
.one.active path {
fill: #f00;
}
const itemSelector = '.one';
const activeClass = 'active';
document.addEventListener('click', ({ target: t }) =>
(t = t.closest(itemSelector)) && t.classList.toggle(activeClass)
);
// или
document.querySelectorAll(itemSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => e.currentTarget.classList.toggle(activeClass));
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 !== '');
for (let i = 0; i < arr.length; i++) {
if (!mustStay(arr[i])) {
for (let j = i--; ++j < arr.length; arr[j - 1] = arr[j]) ;
arr.pop();
}
}
// или
arr.reduceRight((_, n, i, a) => mustStay(n) || a.splice(i, 1), null);
// или
arr.splice(0, arr.length, ...arr.filter(mustStay));
// или
arr.length -= arr.reduce((acc, n, i, a) => (
a[i - acc] = n,
acc + !mustStay(n)
), 0);
[...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 key = 'i';
const attr = `data-${key}`;
const values = [ 'qwe', 'asd', 'zxc' ];
const className = 'класс';
document
.querySelectorAll(values.map(n => `[${attr}="${n}"]`))
.forEach(n => n.classList.add(className));
for (const n of document.querySelectorAll(`[${attr}]`)) {
n.classList.toggle(className, values.includes(n.dataset[key]));
}
на 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;
}