v-model, обновил данные в компоненте; устанавливаете отформатированное значение. Для предотвращения рекурсивной обработки событий input проверяете isTrusted:function updateValue(el) {
el.value = el.value, из которого удалено всё, кроме цифр;
el.dispatchEvent(new Event('input'));
el.value = форматированное значение el.value;
}
function onInput(e) {
if (e.isTrusted) {
updateValue(e.target);
}
}
Vue.directive('number', {
bind(el) {
el.addEventListener('input', onInput);
updateValue(el);
},
update(el) {
updateValue(el);
},
unbind(el) {
el.removeEventListener('input', onInput);
},
});
с минимальным количеством действий
v-for="el in link" на v-for="el in [].concat(link)".
return getValue(objectValus[prop], property);const getValue = (obj, key) => Object
.values(obj ?? {})
.reduce((found, n) => found ?? getValue(n, key), obj?.[key]);
transition-duration: 0ms;.transition: none;.true, не нужна анимация - false. Как-то так.
const result = Object.values(arr.reduce((acc, { id }) => (
(acc[id] ??= { id, count: 0 }).count++,
acc
), {}));function uniqueWithCount(data, key, countKey) {
const getKey = key instanceof Function ? key : n => n[key];
const unique = new Map;
for (const n of data) {
const k = getKey(n);
unique
.set(k, unique.get(k) ?? { ...n, [countKey]: 0 })
.get(k)[countKey]++;
}
return unique;
}const result = Array.from(
uniqueWithCount(arr, 'id', 'count').values(),
({ id, count }) => ({ id, count })
);
function solve(arr) {
const last = arr.reduce((acc, n, i) => (acc[n] = i, acc), {});
return arr.filter((n, i) => last[n] === i);
}function solve(arr) {
const last = new Map(arr.map((n, i) => [ n, i ]));
arr.length -= arr.reduce((acc, n, i, a) => (
a[i - acc] = n,
acc + (i !== last.get(n))
), 0);
return arr;
}const solve = arr => (
arr.splice(0, arr.length, ...[...new Set(arr.reverse())].reverse()),
arr
);
const merge = (arr1, arr2, step) => Array
.from(
{ length: Math.min(arr1.length, 1 + arr2.length / step | 0) },
(_, i) => [ ...arr2.slice(~-i * step, i * step), arr1[i] ]
)
.flat();const merge = (arr1, arr2, step) =>
[].concat(...Array.from(
{ length: Math.min(arr1.length, 1 + arr2.length / step | 0) },
(_, i) => [ arr1[i], ...arr2.slice(i * step, -~i * step) ]
));const merge = (arr1, arr2, step) =>
Array.prototype.flatMap.call(arr1, (n, i) => [
...Object.assign(
i ? Array(step).fill(null) : [],
arr2.slice((i - 1) * step, i * step)
),
n,
]);function merge(arr1, arr2, step) {
const len = arr2.length;
return Array.from(
{ length: len - (len % step) + 1 + len / step | 0 },
(_, i) => {
const j = i / (step + 1) | 0;
return i % (step + 1)
? arr2[i - j - 1]
: arr1[j] ?? null
});
}const c = merge(b, a, 5); - можете воспользоваться любой из этих функций, результаты выдадут одинаковые. Чего может и не быть с другими аргументами. Например:merge('ABCD', [ 1, 2, 3, 4, 5, 6, 7 ], 4)
// первая и четвёртая функции останавливаются на элементе первого массива,
// если во втором массиве не хватает элементов, на заполнение
// очередного промежутка между элементами первого массива
['A', 1, 2, 3, 4, 'B']
// вторая функция остановится после того,
// как отдаст все элементы второго массива
['A', 1, 2, 3, 4, 'B', 5, 6, 7]
// третья функция подставит дефолтные значения
// вместо недостающих элементов второго массива
['A', 1, 2, 3, 4, 'B', 5, 6, 7, null, 'C', null, null, null, null, 'D']merge('ABC', [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], 2)
// 1, 3
['A', 1, 2, 'B', 3, 4, 'C']
// 2
['A', 1, 2, 'B', 3, 4, 'C', 5, 6]
// 4
['A', 1, 2, 'B', 3, 4, 'C', 5, 6, null, 7, 8, null]
const grouped = props.mainPage.room.reduce((acc, n) => (
(acc[n.storey] ??= []).push(n),
acc
), {});{Object.entries(grouped).map(([ groupName, group ]) => (
<div className="group" key={groupName}>
<h3>{groupName}</h3>
{group.map(n => <NumberRoom key={n.id} {...n} />)}
</div>
))}
(function() {
function func(arg) {
console.log(arg, this);
}
let arg = 1;
const f1 = () => func(arg);
const f2 = func.bind(this, arg);
arg = 2;
f1();
f2();
}).call('hello, world!!');
sorted(result, key=lambda n: (n[0], -n[1]))
Array.from(str, n => n < 5 ? 0 : 1).join('')
// или
[...str].reduce((acc, n) => acc + +(n >= 5), '')
// или
''.concat(...str.split('').map(n => Math.floor(n / 5)))
// или
[].map.call(str, n => -~-~-~n >> 3).join``
// или
str.replace(/./g, m => Number('56789'.includes(m)))
// или
str.replace(/[1-4]/g, 0).replace(/[5-9]/g, 1)
const newArr = Array.from(
{ length: arr.length / 2 },
(n, i) => ({ ...arr[i], ...arr[i + arr.length / 2] })
);const numKeys = new Set(arr.flatMap(Object.keys)).size;
const newArr = arr.reduce((acc, n, i, a) => (
Object.assign(acc[i % (a.length / numKeys)] ??= {}, n),
acc
), []);
// или
const numKeys = Object.keys(Object.assign({}, ...arr)).length;
const numObjs = arr.length / numKeys;
const newArr = Array.from(
{ length: numObjs },
(n, i) => Object.assign({}, ...Array.from(
{ length: numKeys },
(m, j) => arr[j * numObjs + i]
))
);const newArr = arr.reduce((acc, n) => {
const [ [ k, v ] ] = Object.entries(n);
const i = acc[0][k] = (acc[0][k] ?? -1) + 1;
(acc[1][i] ??= {})[k] = v;
return acc;
}, [ {}, [] ])[1];