element.insertAdjacentHTML('beforebegin', html);element.before(...new DOMParser()
.parseFromString(html, 'text/html')
.body
.childNodes
);
// или
element.parentNode.insertBefore(
document.createRange().createContextualFragment(html),
element
);element.outerHTML = html + element.outerHTML;
const titleCase = str => str
.split(' ')
.map(n => n.charAt(0).toUpperCase() + n.slice(1).toLowerCase())
.join(' ');const titleCase = str => str
.toLowerCase()
.replace(/(?<=^| +)./g, m => m.toUpperCase());const titleCase = str =>
''.concat(...Array.from(str, (n, i) => {
return n[i && str[~-i] !== ' ' ? 'toLowerCase' : 'toUpperCase']();
}));
(() => {}) instanceof Object // true
const obj = {
a: 69,
b: 187,
get c() {
return this.a + this.b;
},
};const obj = new Proxy({ a: 69, b: 187 }, {
get(target, key) {
return (
key === 'c' ? target.a + target.b :
key === 'd' ? target.a * target.b :
key === 'e' ? target.a - target.b :
target[key]
);
},
});
const container = document;
const selector = 'input[type="checkbox"]';
const sumElements = elements =>
Array.prototype.reduce.call(elements, (acc, n) => acc + +n.value, 0);
const onSumChange = sum => console.log(sum);container.addEventListener('change', function({ target: t }) {
if (t.matches(selector)) {
onSumChange(sumElements(this.querySelectorAll(`${selector}:checked`)));
}
});
container.querySelector(selector).dispatchEvent(new Event('change', { bubbles: true }));const cb = container.querySelectorAll(selector);
let sum = sumElements(Array.prototype.filter.call(cb, n => n.checked));
const onChange = e => onSumChange(sum += e.target.value * [ -1, 1 ][+e.target.checked]);
cb.forEach(n => n.addEventListener('change', onChange));
onSumChange(sum);
str.slice(1).split('&').reduce((acc, n) => (n = n.split('='), acc[n[0]] = n[1], acc), {})
// или
[...str.matchAll(/(\w+)=([^&]*)/g)].reduce((acc, [ , k, v ]) => ({ ...acc, [k]: v }), {})
// или
Object.fromEntries(new URLSearchParams(str))
const STAGES = {
2: 'itemGv',
5: 'itemTm',
};for (const [ key, val ] of Object.entries(items)) {
const s = STAGES[val.stage];
if (s) {
this.client.srem('items', key);
this.emit(s, val);
}
}
const XXX = length => Array
.from({ length }, (n, i) => Array
.from({ length: i + 1 }, (n, i) => i + 1)
.join(','))
.join('\n');
console.log(XXX(5));const XXX = length => Array
.from({ length }, function() {
this.push(-~this.length);
return this.join`,`;
}, [])
.join`\n`;const XXX = length => Array
.from({ length }, (n, i) => Array
.from(Array(++i).keys())
.reduce((acc, n) => acc + (acc && ',') + ++n, ''))
.reduce((acc, n) => acc + (acc && '\n') + n, '');
const SKILLS = {
sport: [ 'running', 'squats', 'snowboarding' ],
music: [ 'guitar', 'drums' ],
};
const filterBySkill = (people, filter) =>
people.filter(({ skills }) =>
skills.every(n => filter.some(m => SKILLS[m].includes(n))) &&
filter.every(n => skills.some(m => SKILLS[n].includes(m)))
);
<div id="time"></div>function setTimer(el, template) {
return setInterval(el => {
const d = new Date();
const timeData = Object.fromEntries([
[ 'h', 'getHours' ],
[ 'm', 'getMinutes' ],
[ 's', 'getSeconds' ],
].map(n => [ n[0], `${d[n[1]]()}`.padStart(2, 0) ]));
el.innerHTML = template.replace(
/\$(\w)/g,
(m, g1) => timeData.hasOwnProperty(g1) ? timeData[g1] : m
);
}, 1000, typeof el === 'string' ? document.querySelector(el) : el);
}
const intervalId = setTimer('#time', '<strong>Сейчас</strong> $h:$m:$s');
function sortChildren(el, key) {
el.append(...Array
.from(el.children, n => [ n, key(n) ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0])
);
}
sortChildren(document.querySelector('.menu'), n => +n.dataset.num);
getElementsByTagName возвращает динамическую коллекцию элементов, т.е. такую, которая автоматически обновляется при добавлении/удалении элементов. Поэтому сейчас у вас происходит следующее: удалили элемент с индексом 0, и у всех остальных элементов изменился индекс на единицу вниз, 0 вместо 1, 1 вместо 2 и т.д. При этом счётчик цикла вы на единицу увеличили, так что на следующей итерации удаляете элемент с индексом 1 - бывший 2. А тот, который был 1 и стал 0 - его вы пропускаете. А после следующего удаления пропускаете ещё один. Ну и т.д. Каждый второй.document.getElementsByTagName("p") на document.querySelectorAll('p'), так вы получите статическую коллекцию элементов.allP от конца к началу:for (let i = allP.length; i--;) {
body.removeChild(allP[i]);
}while (allP.length) {
allP[0].remove();
}body по id - безумие, этот элемент существует в единственном экземпляре и ссылка на него доступна как свойство объекта document. Так что id уберите и замените document.getElementById("body") на document.body.
как улучшить мой код
function fearNotLetter(str) {
const missing = Array
.from(str, n => n.charCodeAt(0))
.find((n, i, a) => n !== a[0] + i);
return missing && String.fromCharCode(missing - 1);
}function fearNotLetter(str) {
for (let i = 0, code = str.charCodeAt(0); ++i < str.length;) {
if (str.charCodeAt(i) !== ++code) {
return String.fromCharCode(code);
}
}
}
Array.prototype.unique = function() {
this.splice(0, this.length, ...new Set(this));
return this;
};Array.prototype.unique = function(key = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const keys = new Set;
this.forEach(n => (this[keys.size] = n, keys.add(getKey(n))));
this.length = keys.size;
return this;
};[ 1, 1, 1, 2 ].unique() // [1, 2]
[ { id: 3 }, { id: 1 }, { id: 1 }, { id: 3 } ].unique('id') // [{id: 3}, {id: 1}]
[ 'a', 'b', 'c', 'd', 'ab', 'bc' ].unique(n => n.length) // ['a', 'ab']
function translatePigLatin(str) {
const x = str.search(/[aioue]/);
return x > 0
? `${str.slice(x)}${str.slice(0, x)}ay`
: `${str}${x ? '' : 'w'}ay`;
}