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 {
const result = tasks[index]();
results[index] = result instanceof Promise ? await result : result;
} 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)
Я новичок в python
if change_index <= len(alphabet): result_text += alphabet[change_index]
function Ranges(props) {
const onChange = ({ target: t }) => {
const index = +t.dataset.index;
const value = +t.value;
const values = props.values.map((n, i) => i === index ? value : n);
if (props.max >= values.reduce((acc, n) => acc + n, 0)) {
props.onChange(values);
}
};
return (
<div>
{props.values.map((n, i) => (
<div>
<input
type="range"
data-index={i}
max={props.max}
value={n}
onChange={onChange}
/>
{n}
</div>
))}
</div>
);
}
const groupedAndSortedArr = Object
.values(arr.reduce((acc, n) => ((acc[n[0]] ??= []).push(n), acc), {}))
.sort((a, b) => a[0][0].localeCompare(b[0][0]));
str.split('=').pop()
// или
str.slice(str.indexOf('=') + 1)
str.replace(/[^=]*=/, '')
// или
str.match(/(?<==).*/)[0]
// или
/[^=]*$/.exec(str).shift()
new URLSearchParams(str).get('sort')
Array
.from(new URLSearchParams(str))
.reduce((acc, [ k, v ]) => (
k.endsWith('[]')
? (acc[k.slice(0, -2)] ??= []).push(v)
: acc[k] = v,
acc
), {})