Преглед на файлове

Adds some chunking functions

main
Eric Amodio преди 3 години
родител
ревизия
57b8b3373c
променени са 2 файла, в които са добавени 51 реда и са изтрити 0 реда
  1. +11
    -0
      src/system/array.ts
  2. +40
    -0
      src/system/iterable.ts

+ 11
- 0
src/system/array.ts Целия файл

@ -6,6 +6,17 @@ import {
xor as _xor,
} from 'lodash-es';
export function chunk<T>(source: T[], size: number): T[][] {
const chunks = [];
let index = 0;
while (index < source.length) {
chunks.push(source.slice(index, size + index));
index += size;
}
return chunks;
}
export function countUniques<T>(source: T[], accessor: (item: T) => string): Record<string, number> {
const uniqueCounts = Object.create(null) as Record<string, number>;
for (const item of source) {

+ 40
- 0
src/system/iterable.ts Целия файл

@ -1,5 +1,45 @@
'use strict';
export function* chunk<T>(source: T[], size: number): Iterable<T[]> {
let chunk: T[] = [];
for (const item of source) {
if (chunk.length < size) {
chunk.push(item);
continue;
}
yield chunk;
chunk = [];
}
if (chunk.length > 0) {
yield chunk;
}
}
export function* chunkByStringLength(source: string[], maxLength: number): Iterable<string[]> {
let chunk: string[] = [];
let chunkLength = 0;
for (const item of source) {
let length = chunkLength + item.length;
if (length > maxLength && chunk.length > 0) {
yield chunk;
chunk = [];
length = item.length;
}
chunk.push(item);
chunkLength = length;
}
if (chunk.length > 0) {
yield chunk;
}
}
export function count<T>(source: Iterable<T> | IterableIterator<T>, predicate?: (item: T) => boolean): number {
let count = 0;
let next: IteratorResult<T>;

Зареждане…
Отказ
Запис