const countWithKey = (arr, key) => arr.filter(n => key in n).length;
console.log(countWithKey(arr, 'ключ'));
const sum = (data, val = n => n) =>
Array.prototype.reduce.call(
data,
(acc, n) => acc + val(n),
0
);
console.log(sum(arr, obj => obj.hasOwnProperty('ключ')));
sum([ 1, 2, 3 ]) // 6
), так и более сложные варианты. Например, есть массив, представляющий содержимое корзины с товарами (цена, количество), надо посчитать общую стоимость:const cart = [
{ price: 100, count: 5 },
{ price: 10, count: 6 },
{ price: 1, count: 7 },
];
const total = sum(cart, item => item.price * item.count); // 567
const likes = sum(document.querySelectorAll('.btn_like .btn__counter'), n => +n.innerText);
function Counter(data, key = n => n) {
const counted = new Map;
for (const n of data) {
const k = key(n);
counted.set(k, (counted.get(k) ?? 0) + 1);
}
return k => counted.get(k) ?? 0;
}
const keyExists = Counter(arr, obj => Object.hasOwn(obj, 'ключ'));
console.log(keyExists(true)); // смотрим, у скольких элементов массива ключ есть
console.log(keyExists(false)); // и у скольких нет
const str = 'hello, world!!';
const chars = Counter(str);
console.log(chars('h')); // 1
console.log(chars('!')); // 2
console.log(chars('x')); // 0
const persons = [
{ name: 'Вася', birthday: new Date('1999-05-22') },
{ name: 'Маша', birthday: new Date('2004-03-06') },
{ name: 'Катя', birthday: new Date('1976-05-15') },
{ name: 'Петя', birthday: new Date('1987-04-18') },
{ name: 'Коля', birthday: new Date('2000-01-01') },
{ name: 'Дима', birthday: new Date('2003-05-09') },
{ name: 'Миша', birthday: new Date('1996-02-29') },
{ name: 'Таня', birthday: new Date('1981-03-12') },
{ name: 'Олег', birthday: new Date('1992-08-24') },
];
const birthMonths = Counter(
persons,
({ birthday }) => birthday.toLocaleString('ru-RU', { month: 'long' })
);
console.log(birthMonths('май')); // в мае родилось три человека
console.log(birthMonths('март')); // в марте два
console.log(birthMonths('октябрь')); // а в октябре никто
function* naturalNumbers(n) {
for (let i = 1; i <= n; i++) {
yield i;
}
}
const numLengths = Counter(naturalNumbers(100), num => `${num}`.length);
console.log(numLengths(2)); // среди первых ста натуральных чисел - девяносто двухзначных
console.log(numLengths(3)); // и одно трёхзначное
console.log(numLengths(0)); // число из нуля знаков? - конечно же нет таких
function objToString(val, tabSize = 2, depth = 0, noIndent = false) {
const indent = ' '.repeat(tabSize * depth);
return (noIndent ? '' : indent) + (
val instanceof Array
? `[\n${val.map(n => objToString(n, tabSize, depth + 1)).join(',\n')}\n${indent}]`
: val instanceof Object
? `{\n${Object
.entries(val)
.map(n => n.map((m, i) => objToString(m, tabSize, depth + 1, i)).join(': '))
.join(',\n')}\n${indent}}`
: typeof val === 'string'
? `"${val}"`
: val
);
}
console.log(objToString({
numbers: [ 69, 187, 666 ],
strings: [ 'hello, world!!', 'fuck the world', 'fuck everything' ],
falsy_values: [ 0, '', NaN, false, null, undefined ],
object: { xxx: true, yyy: Infinity, zzz: { '!&$': [ [ [ -1 ] ] ] } }
}));
const insert = (str, substr, ...indices) => [ 0 ]
.concat(indices)
.filter(n => 0 <= n && n <= str.length)
.sort((a, b) => a - b)
.map((n, i, a) => str.slice(n, a[i + 1]))
.join(substr);
// или
const insert = (str, substr, ...indices) => indices
.sort((a, b) => b - a)
.reduce((acc, n) => (
0 <= n && n <= str.length && acc.splice(n, 0, substr),
acc
), [...str])
.join('');
// или
const insert = (str, substr, ...indices) =>
''.concat(...Array.from(
{ length: -~str.length },
function(_, i) {
return substr.repeat(this[i] ?? 0) + str.charAt(i);
},
indices.reduce((acc, n) => (acc[n] = -~acc[n], acc), {})
));
const insert = (str, substr, ...indices) => indices
.filter(n => 0 <= n && n <= str.length)
.sort((a, b) => a - b)
.reduce((acc, n, i) =>
acc.replace(RegExp(`(?<=^.{${n + i * substr.length}})`), substr)
, str);
// ваш случай
const str = insert(`${number}`, '-', 3, 5, 8, 10);
// вставлять можно больше одного символа
insert('abc', ' --> ', 1, 2) // 'a --> b --> c'
// можно по одному индексу несколько раз делать вставку
insert('abc', '~', 0, 0, 0) // '~~~abc'
// за границы строки вставка не выполняется,
// за исключением позиции сразу же после конца строки
insert('abc', '!', -1, 3, 4) // 'abc!'
вторая не работает
.grade-item
обрабатывать, а только те, у кого в предках тот же .grade-item-block
, что и у кликнутого.const container = document.querySelector('.nav-student-new-lesson');
const blockSelector = '.grade-item-block';
const itemSelector = `${blockSelector} .grade-item`;
const colors = {
grades: [
[ 5, 'rgba(150, 255, 0, 0.3)' ],
[ 3, 'rgba(255, 150, 0, 0.3)' ],
[ 1, 'rgba(255, 0, 0, 0.3)' ],
],
default: 'white',
};
function updateGrade(item) {
const items = item.closest(blockSelector).querySelectorAll(itemSelector);
const grade = 1 + Array.prototype.indexOf.call(items, item);
const color = colors.grades.find(n => n[0] <= grade)[1];
items.forEach((n, i) => n.style.background = i < grade ? color : colors.default);
}
container.addEventListener('click', e => {
const item = e.target.closest(itemSelector);
if (item) {
updateGrade(item);
}
});
.grade-item
:container.querySelectorAll(itemSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => updateGrade(e.currentTarget));
function generator($str, $params) {
$result = [];
if (count($params)) {
$key = key($params);
$values = is_array($params[$key]) ? $params[$key] : [ $params[$key] ];
unset($params[$key]);
foreach ($values as $val) {
array_push($result, ...generator(str_replace("{{$key}}", $val, $str), $params));
}
} else {
$result[] = $str;
}
return $result;
}
const listEl = document.querySelector('#list');
const activeClass = 'active';
let index = 0;
next(0);
document.addEventListener('keydown', function(e) {
const step = ({
ArrowDown: 1,
ArrowUp: -1,
})[e.key];
if (step) {
next(step);
}
});
function next(step) {
const elems = listEl.children;
elems[index].classList.remove(activeClass);
index = Math.max(0, Math.min(elems.length - 1, index + step));
// или, если надо, чтобы при переходе от последнего к следующему элементу
// активным становился первый, а при переходе от первого к предыдущему
// активным становился последний
// index = (index + step + elems.length) % elems.length;
elems[index].classList.add(activeClass);
}
думаю что тут проблема из за proxy
Vue.toRaw(this.map).geoObjects.add(placemark);
this.map = Vue.markRaw(new ymaps.Map(this.$refs.map, {
...
card_gallery.on('click', function(swiper, e) {
const index = swiper.slides.indexOf(e.target.closest('.swiper-slide'));
if (index !== -1) {
single_gallery.slideTo(index);
}
});
slideToClickedSlide: true
в настройки card_gallery. Object.values(Object.fromEntries(arr.map(n => [ n.user.id, n ])))
// или, если в результирующий массив должны попадать те из "одинаковых" элементов,
// что расположены в исходном массиве первыми
Object.values(arr.reduce((acc, n) => (acc[n.user.id] ??= n, acc), {}))
// или, если также надо сохранять взаимное расположение элементов
arr.filter(function({ user: { id: n } }) {
return !(this[n] = this.hasOwnProperty(n));
}, {})
function* unique(data, key = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const keys = new Set;
for (const n of data) {
const k = getKey(n);
if (!keys.has(k)) {
keys.add(k);
yield n;
}
}
}
const result = [...unique(arr, n => n.user.id)];
.Array.from(unique([{id: 1}, {id: 2}, {id: 1}, {id: 1} ], 'id')) // [{id: 1}, {id: 2}]
''.concat(...unique('ABBA')) // 'AB'
.for (const n of unique(Array(20).keys(), n => Math.sqrt(n) | 0)) {
console.log(n); // 0 1 4 9 16
}
.list-enter-from {
transition-group
следует добавить параметр appear
. fetch('https://jsonplaceholder.typicode.com/todos/1')
1
.const [data, setData] = useState(null);
{data.map(item => (
null
метод map
? - погуглите, разберитесь. Ну и замените null
на []
. const radios = document.querySelectorAll('[name="radios"]');
const selects = Array.from(radios, n => n.nextElementSibling);
const onChange = e => selects.forEach(n => n.disabled = n !== e.target.nextElementSibling);
radios.forEach(n => n.addEventListener('change', onChange));
data.each_value{|n|
puts("#{n[:name]}: вес #{n[:weight]} г., количество #{n[:qty]} шт.")
}
const arithmeticProgression = ({ length, a1 = 0, d = 1 }) =>
Array.from(
{ length },
(n, i) => a1 + i * d
);
const arr = arithmeticProgression({
length: 10,
a1: 6,
d: 3,
});
function* arithmeticProgression(a1, d, length) {
for (let i = 0; i < length; i++) {
yield a1 + i * d;
}
}
for (const n of arithmeticProgression(100, 10, 5)) {
console.log(n);
}
console.log(Array.from(arithmeticProgression(10, -7, 10)));
def fucking_filter(arr, max_count, key=lambda n: n):
filtered = []
count = {}
for n in arr:
k = key(n)
count[k] = count.get(k, 0) + 1
if count[k] <= max_count:
filtered.append(n)
return filtered
for n in fucking_filter(genres, N):
print(n)
хочу сделать задержку ввода
methods: {
onInput: debounce(function(val) {
this.debouncedInput = val;
}, 500),
...
<v-text-field
@input="onInput"
...
computed: {
count() {
return this.orders.map(n => n.count);
},
},
watch: {
count: debounce(function(newVal, oldVal) {
this.debouncedInput = newVal.find((n, i) => n !== oldVal[i]);
}, 500),
},
data: () => ({
links: [ 'tasks', 'kanban', 'activity', 'calendar', 'files' ],
}),
ul
li(v-for="n in links")
router-link(:to="{ name: n }") {{ n }}
.marker
div(v-for="n in links" :class="[ `select${n}`, $route.name === n ? 'active' : '' ]")
span
const certificate = ref({});
shortingTechItems(certificate.pto)
прилетает undefined
В чем проблема
как исправить?
- const shortingTechItems = (item) => {
- const arr = [];
- item.map((i) => {
- arr.push(Number(i.replace(/\D+/g, "")));
- });
- return arr;
- };
+ const shortingTechItems = items => items.map(n => +n.replace(/\D/g, ''));
props: [ 'value' ],
provide() {
return {
radioGroup: this,
};
},
props: [ 'value' ],
inject: [ 'radioGroup' ],
<input
type="radio"
:value="value"
:checked="radioGroup.value === value"
@change="radioGroup.$emit('input', value)"
>
props: [ 'modelValue' ],
emits: [ 'update:modelValue' ],
setup(props, { emit }) {
provide('radioGroupValue', computed({
get: () => props.modelValue,
set: v => emit('update:modelValue', v),
}));
},
props: [ 'value' ],
setup() {
return {
radioGroupValue: inject('radioGroupValue'),
};
},
<input
type="radio"
:value="value"
v-model="radioGroupValue"
>