Код, который работает некорректно...
Object.freeze
назначить новое свойство уже не получится. Можно записать итератор в прототип массива (ну и после того, как он отработает, вернуть оригинальный итератор на место):const originalIterator = Array.prototype[Symbol.iterator];
Array.prototype[Symbol.iterator] = function() {
let i = -1;
return {
next: () => (i += 2) < arr.length
? { done: false, value: this[i] }
: { done: true },
};
};
setTimeout(() => Array.prototype[Symbol.iterator] = originalIterator, 0);
<div className="todoListMain"> <div className="header">
.todoListMain.header input {
.todoListMain
и .header
куда потерялся? Ну и с остальными стилями косяк тот же. const result = arr.flat();
// или
const result = Array.prototype.concat.apply([], arr);
// или
const result = arr.reduce((acc, n) => (acc.push(...n), acc), []);
// или
const result = [];
for (const n of arr) {
for (const m of n) {
result[result.length] = m;
}
}
seachCityName - обычная строка
seachCityName.value
. const outerClass = 'filter__item';
const innerClass = 'filter__checkgroup-count';
OUTER:
for (const n of document.getElementsByClassName(outerClass)) {
for (const m of n.getElementsByClassName(innerClass)) {
if (Number(m.innerText)) {
continue OUTER;
}
}
n.hidden = true;
// или
n.style.display = 'none';
// или
n.style.setProperty('visibility', 'hidden');
// или
n.style.cssText += 'opacity: 0';
// или
n.setAttribute('style', 'transform: scale(0)');
}
.hidden {
display: none;
}
document.querySelectorAll(`.${outerClass}`).forEach(n => {
n.classList.toggle('hidden', !Array.prototype.some.call(
n.querySelectorAll(`.${innerClass}`),
m => +m.textContent
));
});
function isEqual(a, b) {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(n => a[n] === b[n]);
}
const result = arr1.concat(arr2.filter(n => arr1.every(m => !isEqual(n, m))));
const unique = function(arr, keys = n => n) {
const picked = new Map;
return arr.filter((...args) => {
const p = []
.concat(keys(...args))
.reduce((acc, k) => acc.set(k, acc.get(k) ?? new Map).get(k), picked);
return !p.set(this, p.has(this)).get(this);
});
}.bind(Symbol());
const result = unique([ ...arr1, ...arr2 ], n => [ n.teamId, n.userId ]);
data: () => ({
items: [
'hello, world!!',
'fuck the world',
'fuck everything',
],
}),
<ul>
<li
v-for="(n, i) in items"
v-text="n"
@click="$set(items, i, `${n}!`)"
></li>
</ul>
const zip = (...arrs) =>
arrs[0]?.map((n, i) => arrs.map(m => m[i])) ?? [];
const result = zip(arr1, arr2);
const zip = (arrs, defaultValue = null) =>
Array.from(
{ length: Math.max(...arrs.map(n => n.length)) },
(n, i) => arrs.map(m => i < m.length ? m[i] : defaultValue)
);
// или
const zip = (arrs, defaultValue = null) =>
arrs.reduce((acc, n, i) => (
n.forEach((m, j) => (acc[j] ??= Array(arrs.length).fill(defaultValue))[i] = m),
acc
), []);
const result = zip([ arr1, arr2 ]);
.zip([ [ 1, 2, 3 ], [], [ 99 ] ], Infinity)
- в результате получим[
[ 1, Infinity, 99 ],
[ 2, Infinity, Infinity ],
[ 3, Infinity, Infinity ]
]
function* zip(data, defaultValue = null) {
const iterators = Array.from(data, n => n[Symbol.iterator]());
for (let doneAll = false; doneAll = !doneAll;) {
const values = [];
for (const n of iterators) {
const { value, done } = n.next();
values.push(done ? defaultValue : value);
doneAll &&= done;
}
if (!doneAll) {
yield values;
}
}
}
const result = [...zip([ arr1, arr2 ])];
.Array.from(zip((function*() {
yield [ , true, false, NaN ];
yield 'abcde';
yield Array(3).keys();
})()))
[
[ undefined, 'a', 0 ],
[ true, 'b', 1 ],
[ false, 'c', 2 ],
[ NaN, 'd', null ],
[ null, 'e', null ]
]
const chunked = (arr, chunkSize) =>
arr.reduce((acc, n, i) => (
(i % chunkSize) || acc.push([]),
acc.at(-1).push(n),
acc
), []);
console.log(chunked([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], 3));
const group = (data, key) =>
Array.prototype.reduce.call(
data,
(acc, n, i, a) => ((acc[key(n, i, a)] ??= []).push(n), acc),
{}
);
const chunked = (data, chunkSize) =>
Object.values(group(data, (_, i) => i / chunkSize | 0));
console.log(chunked('0123456789', 3));
console.log(chunked(document.querySelectorAll('img'), 5));
const chunked = (data, chunkSize, slice = data.slice) =>
Array.from(
{ length: Math.ceil(data.length / chunkSize) },
function(_, i) {
return this(i * chunkSize, (i + 1) * chunkSize);
},
(slice instanceof Function ? slice : Array.prototype.slice).bind(data)
);
console.log(chunked('abcdefghij', 4)); // так кусками будут тоже строки
console.log(chunked('abcdefghij', 4, [].slice)); // а так - массивы
console.log(chunked($('img'), 5));
function* chunked(data, chunkSize) {
let chunk = [];
for (const n of data) {
if (chunk.push(n) === chunkSize) {
yield chunk;
chunk = [];
}
}
if (chunk.length) {
yield chunk;
}
}
console.log(Array.from(chunked([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], 3)));
console.log([...chunked(document.querySelectorAll('img'), 5)]);
for (const n of chunked(Array(10).keys(), 4)) {
console.log(n);
}
const index = arr1.findIndex(n => arr2.indexOf(n) !== -1);
// просто массив индексов
const indices = arr1.reduce((acc, n, i) => (arr2.includes(n) && acc.push(i), acc), []);
// объект вида { элемент: индекс первого вхождения }
const indices = arr2.reduce((acc, n) => (
acc[0].hasOwnProperty(n) && (acc[1][n] = acc[0][n]),
acc
), [ arr1.reduce((acc, n, i) => (acc[n] ??= i, acc), {}), {} ])[1];
// Map вида { элемент: массив всех индексов данного элемента }
const indices = arr1.reduce((acc, n, i) => (
acc[0].has(n) && acc[1].set(n, acc[1].get(n) ?? []).get(n).push(i),
acc
), [ new Set(arr2), new Map ])[1];
arr
.group_by{|n| n[:name]}
.map{|n| { name: n[0], value: n[1].sum{|m| m[:value]} }}
const runTasks = (tasks, max = 1) =>
new Promise(resolve => {
const results = Array(tasks.length).fill(null);
let started = 0;
let finished = 0;
for (let i = Math.max(1, Math.min(max, tasks.length)); i--; run()) ;
async function run() {
if (finished === tasks.length) {
resolve(results);
} else if (started < tasks.length) {
const index = started++;
try {
results[index] = await tasks[index]();
} catch (e) {
results[index] = e;
}
finished++;
run();
}
}
});
const sendRequests = (urls, ...args) =>
runTasks(urls.map(n => () => fetch(n).then(r => r.json())), ...args);
const printf = (str, ...params) =>
str.replace(/\$(\d+)/g, (m, g1) => params[~-g1] ?? m);
массивСДанными.map((n, i) => {
const Component = i % через_сколько_там_надо_чередовать_компоненты
? КомпонентРаз
: КомпонентДва;
return <Component {...n} />;
})
.item:nth-child(2n) {
background-color: red;
}
<div v-for="n in items" class="item">
<div v-for="(n, i) in items" :style="i & 1 && { backgroundColor: 'red' }">
strval(intval($str))
preg_replace('~^0+~', '', $str)