const today = new Date().getDate();
const select = document.querySelector('select');
const toggle = option => option.disabled = option.value < today;
select.querySelectorAll('option').forEach(toggle);
// или
Array.prototype.forEach.call(select, toggle);
// или
for (const n of select.options) {
toggle(n);
}
// или
for (let i = 0; i < select.children.length; i++) {
toggle(select.children[i]);
}
// или
(function next(i, n = select.item(i)) {
if (n) {
toggle(n);
next(-~i);
}
})(0);
// или
const next = n => n && (next(n.nextElementSibling), toggle(n));
next(select.firstElementChild);
const duplicateContent = el =>
// можно добавить копии вложенных узлов
el.append(...el.cloneNode(true).childNodes);
// или добавить копию разметки
// el.insertAdjacentHTML('beforeend', el.innerHTML);
// или перезаписать разметку в удвоенном виде
// el.innerHTML += el.innerHTML;
// el.innerHTML = el.innerHTML.repeat(2);
// el.innerHTML = Array(3).join(el.innerHTML);
// el.innerHTML = String.prototype.concat.apply('', Array(2).fill(el.innerHTML));
// el.innerHTML = el.innerHTML.replace(/.+/, '$&$&');
// el.innerHTML = /(.+)/.exec(el.innerHTML).join``;
document.querySelectorAll('.btn').forEach(duplicateContent);
// или
for (const n of document.getElementsByClassName('btn')) {
duplicateContent(n);
}
const getDuplicatesIndex = (arr, key = n => n) =>
Object.fromEntries(Object
.entries(arr.reduce((acc, n, i) => ((acc[key(n)] ??= []).push(i), acc), {}))
.filter(n => n[1].length > 1)
);
Map
:const getDuplicatesIndex = (arr, key = n => n) =>
new Map(Array
.from(arr.reduce((acc, n, i) => {
const k = key(n);
acc.set(k, acc.get(k) ?? []).get(k).push(i);
return acc;
}, new Map))
.filter(n => ~-n[1].length)
);
const longestStr = arr.reduce((max, n) => max.length > n.length ? max : n, '');
// или
const longestStr = arr.sort((a, b) => b.length - a.length)[0];
// или
const longestStr = arr.reduce((acc, n) => (acc[n.length] = n, acc), []).pop();
function max(data, key = n => n) {
const getVal = key instanceof Function ? key : n => n[key];
let result = null;
for (const n of data) {
const val = getVal(n);
if (!result || result[1] < val) {
result = [ n, val ];
}
}
return result?.[0];
}
const longestStr = max(arr, 'length');
const getRepetition = (arr, repeated) => Array
.from(arr.reduce((acc, n) => acc.set(n, -~acc.get(n)), new Map))
.reduce((acc, n) => (n[1] === repeated && acc.push(n[0]), acc), []);
function getRepetition(arr, repeated) {
const result = [];
const count = {};
for (const n of arr) {
if (!count.hasOwnProperty(n)) {
count[n] = 0;
}
count[n]++;
}
for (const n in count) {
if (count[n] === repeated) {
result.push(+n);
}
}
return result;
}
$(document).click('.e-1', function(event) { console.log(event.target) });
$(document).on('click', '.e-1', function(e) {
console.log(e.currentTarget);
});
'*'
в качестве результата, реально вы выдаёте '*\n'
..join('\n')
. Ну и ещё пробелов не хватает после звёздочек.const christmasTree = length =>
Array.from({ length }, (n, i) => (
n = ' '.repeat(length - i - 1),
n + '*'.repeat(i * 2 + 1) + n
)).join('\n');
const random = arr => arr[Math.random() * arr.length | 0];
const item = random(random(Object.values(state.themes)));
const item = random(Object.values(state.themes).flat());
function weightedRandom(arr, key = () => 1) {
const val = key instanceof Function ? key : n => n[key];
const max = arr.reduce((acc, n) => acc + val(n), 0);
return () => {
let rand = Math.random() * max;
return arr.find(n => (rand -= val(n)) < 0);
};
}
const randomArr = weightedRandom(Object.values(state.themes), 'length');
// ...
const item = random(randomArr());
const elements = Array.prototype.filter.call(
document.querySelectorAll('.green'),
(n, i, a) => n.nextElementSibling !== a[i + 1]
);
'.green + .green'
, или при фильтрации дополнительно проверяйте, что n.previousElementSibling === a[i - 1]
. str.split('/').pop()
// или
str.match(/[^\/]+$/)[0]
// или
str.replace(/.*\//, '')
// или
str.slice(str.lastIndexOf('/') + 1)
// или
Array.from(str).reduce((acc, n) => n === '/' ? '' : acc + n, '')
// или
[...str].filter((n, i, a) => !a.includes('/', i)).join('')
const itemSelector = '.header';
const buttonSelector = `${itemSelector} .delete_block`;
document.querySelectorAll(buttonSelector).forEach(function(n) {
n.addEventListener('click', this);
}, ({ currentTarget: t }) => {
while (!(t = t.parentNode).matches(itemSelector)) ;
t.replaceWith();
});
// или
document.addEventListener('click', e => e
.target
.closest(buttonSelector)
?.closest(itemSelector)
.remove()
);
function merge(key, ...arrs) {
const getKey = key instanceof Function ? key : n => n[key];
const result = new Map;
arrs.forEach(arr => arr.forEach(n => {
const k = getKey(n);
result.set(k, Object.assign(result.get(k) ?? {}, n));
}));
return [...result.values()];
}
const result = merge('id', arr1, arr2, arr3);
. const getTruthyKeys = obj =>
Object
.entries(obj)
.filter(n => n[1])
.map(n => n[0]);
for([key, value] of Object.entries(item)) {
const obj = new Proxy({
a: 0,
b: 1,
c: 2,
}, {
get: () => Math.round(Math.random()),
});
console.log(Array.from({ length: 10 }, () => getTruthyKeys(obj)));
const replaceValues = (val, test, replacer) =>
val instanceof Array
? val.map(n => replaceValues(n, test, replacer))
: val instanceof Object
? Object.fromEntries(Object
.entries(val)
.map(([ k, v ]) => [
k,
test(k, v)
? replacer(v)
: replaceValues(v, test, replacer)
])
)
: val;
const newData = replaceValues(
data,
k => k.includes('Date'),
v => v.replace(/(\d+)-(\d+)-/, '$2.$1.')
);
$('.content_toggle').click(function() {
const $button = $(this);
$(`#box-${this.id.split('-').pop()}`).slideToggle(300, function() {
const isHidden = $(this).is(':hidden');
$button
.text(isHidden ? 'Показать текст' : 'Скрыть текст')
.toggleClass('open', !isHidden);
});
return false;
});
$(this).closest('здесь селектор общего предка').find('.content_block')
$(this).next()
$('.content_block').eq($('.content_toggle').index(this))