main.innerHTML = arr.reduceRight((content, tag) => `<${tag}>${content}</${tag}>`, '');
// или
main.append(arr.reduceRight((content, tag) => {
const el = document.createElement(tag);
el.append(content);
return el;
}, ''));
main.insertAdjacentHTML('beforeend', (function next(i) {
return arr[i] ? `<${arr[i]}>${next(-~i)}</${arr[i]}>` : '';
})(0));
// или
arr.forEach(function(tag) {
this[0].appendChild(document.createElement(tag));
this[0] = this[0].lastChild;
}, [ main ]);
const merge = (target, ...sources) =>
sources.reduce((acc, n) => (
Object.entries(n).forEach(([ k, v ]) =>
acc[k] = v instanceof Object
? merge(acc[k] instanceof Object ? acc[k] : {}, v)
: v
),
acc
), target);
const result = merge({}, ...arrayObj);
const sorted = (data, key) => Array
.from(data, n => [ key(n), n ])
.sort(([a], [b]) => a < b ? -1 : +(a > b))
.map(n => n[1]);
const sortChildren = (el, key) =>
el.append(...sorted(el.children, key));
<button data-order="-1">От большего к меньшему</button>
<button data-order="+1">От меньшего к большему</button>
.catalog-items
(вес элемента - число внутри, умноженное на направление сортировки), кликнутой кнопке класс добавляем, у остальных убираем:const wrapper = document.querySelector('.catalog-items');
const buttons = document.querySelectorAll('[data-order]');
buttons.forEach(n => n.addEventListener('click', onClick));
function onClick({ target: t }) {
const order = +t.dataset.order;
sortChildren(wrapper, el => parseInt(el.innerText) * order);
buttons.forEach(n => n.classList.toggle('active', n === t));
}
В документации не нашёл явных примеров.
options: {
plugins: {
legend: {
onClick(e, legendItem, { chart }) {
this.legendItems.forEach((n, i) => {
chart.getDatasetMeta(i).hidden = n !== legendItem && (legendItem.hidden || !n.hidden);
});
chart.update();
},
},
},
},
nextEl: prevRef.current
const [ swiper, setSwiper ] = useState();
<Swiper
onSwiper={setSwiper}
...
- ref={prevRef}
+ onClick={() => swiper.slidePrev()}
data: () => ({
maxlen: 10,
items: [
'hello, world!!',
'fuck the world',
'fuck everything',
'1234567890',
'Lorem ipsum dolor sit amet, consectetur adipiscing elit,',
],
}),
methods: {
short1: (str, maxlen) => str.length <= maxlen ? str : str.slice(0, maxlen) + '...',
short2: (str, maxlen) => str.substring(0, maxlen) + (str.charAt(maxlen) && '...'),
short3: (str, maxlen) => str.replace(RegExp(`(.{${maxlen}}).+`), '$1...'),
short4: (str, maxlen) => str.replace(RegExp(`(?<=.{${maxlen}}).+`), '...'),
},
<input type="range" min="1" max="20" v-model="maxlen">
<span>{{ maxlen }}</span>
<div v-for="n in items">
<div v-text="short1(n, maxlen)"></div>
<div v-html="short2(n, maxlen)"></div>
<div :text-content.prop="short3(n, maxlen)"></div>
<div>{{ short4(n, maxlen) }}</div>
</div>
const [ zero, one, two, three, four, five, six, seven, eight, nine ] = Array.from(
{ length: 10 },
(_, i) => f => f instanceof Function ? f(i) : i
// или
// (_, i) => f => f?.(i) ?? i
);
const plus = a => b => b + a;
const minus = a => b => b - a;
const times = a => b => b * a;
const dividedBy = a => b => b / a | 0;
const sortDigits = num => +[...`${num}`].sort((a, b) => b - a).join('');
const sortDigits = num => ''.concat.apply('', num.toString().split('').sort().reverse()) - 0;
const sortDigits = num => Number(Array
.from('' + num)
.reduce((acc, n) => (acc[n]++, acc), Array(10).fill(0))
.reduceRight((acc, n, i) => acc + String(i).repeat(n), '')
);
const sortDigits = num => Array
.prototype
.reduce
.call(String(num), (acc, n) => ((acc[9 - n] ??= []).push(n | 0), acc), [])
.flat()
.reduce((acc, n) => acc * 10 + n, 0);
from collections import Counter
item = Counter(arr).most_common(1)[0][0]
computed: {
columns() {
return Object.keys(this.fedresurs.find(n => n.items.length)?.items[0] ?? {});
},
},
<table v-for="messages in fedresurs">
<caption>{{ messages.title }}</caption>
<thead>
<tr>
<th v-for="column in columns">{{ column }}</th>
</tr>
</thead>
<tbody>
<tr v-for="item in messages.items">
<td v-for="column in columns">{{ item[column] }}</td>
</tr>
</tbody>
</table>
products.insert(contentsOf: drinks, at: 0)
.for n in drinks.reversed() {
products.insert(n, at: 0)
}
// или
for i in (0 ..< drinks.count) {
products.insert(drinks[i], at: i)
}
Использую yandex-map@beta
пытаюсь изменить параметр zoom в YandexMap, но не работает, и что-то мне подсказывает, что не всё так просто
setup() {
...
let map = null;
return {
...
onCreate: e => map = e,
updateZoom: z => map.setZoom(Math.max(1, Math.min(19, map.getZoom() + z))),
};
},
<yandex-map
...
@created="onCreate"
/>
...
<button @click="updateZoom(+1)">+</button>
<button @click="updateZoom(-1)">-</button>
срабатывает дважды, а в последующие разы увеличивается в разы
useEffect(() => { window.addEventListener('keydown', onKeyPress); }, [focus])
useEffect(() => {
const onKeyDown = ({ keyCode }) => {
if (keyCode === 39) {
setFocus(focus => focus + 1);
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, []);
state = {
phones: [
{ id: 1, title: '', number: '' },
],
}
onChange = ({ target: { value, name, dataset: { index } } }) => {
this.setState(({ phones }) => ({
phones: phones.map((n, i) => +index === i
? { ...n, [name]: value }
: n
),
}));
}
addPhone = () => {
this.setState(({ phones }) => ({
phones: [
...phones,
{
id: 1 + Math.max(...phones.map(n => n.id)),
title: '',
number: '',
},
],
}));
}
delPhone = ({ target: { dataset: { index } } }) => {
this.setState(({ phones }) => ({
phones: phones.filter((n, i) => i !== +index),
}));
}
render() {
return (
<div>
{this.state.phones.map((n, i) => (
<div key={n.id}>
<input name="title" data-index={i} value={n.title} onChange={this.onChange} />
<input name="number" data-index={i} value={n.number} onChange={this.onChange} />
{i ? <button data-index={i} onClick={this.delPhone}>x</button> : null}
</div>
))}
<button onClick={this.addPhone}>Add</button>
</div>
);
}
data: () => ({
currencies: [
{ title: 'рубль', rate: 1, val: 0 },
{ title: 'доллар', rate: 62.65, val: 0 },
{ title: 'евро', rate: 60.90, val: 0 },
],
}),
methods: {
onInput({ rate, val }) {
this.currencies.forEach(n => n.val = val * rate / n.rate);
},
},
<div v-for="n in currencies">
<input
v-model.number="n.val"
@input="onInput(n)"
type="number"
min="0"
>
{{ n.title }}
</div>