Browse Source

Adds some chunking functions

main
Eric Amodio 4 years ago
parent
commit
57b8b3373c
2 changed files with 51 additions and 0 deletions
  1. +11
    -0
      src/system/array.ts
  2. +40
    -0
      src/system/iterable.ts

+ 11
- 0
src/system/array.ts View File

@ -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 View File

@ -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>;

Loading…
Cancel
Save