UNPKG

@mcabreradev/filter

Version:

A powerful, SQL-like array filtering library for TypeScript and JavaScript with advanced pattern matching, MongoDB-style operators, deep object comparison, and zero dependencies

112 lines 2.69 kB
export function* take(iterable, count) { if (count <= 0) return; let taken = 0; for (const item of iterable) { yield item; taken++; if (taken >= count) break; } } export function* skip(iterable, count) { let skipped = 0; for (const item of iterable) { if (skipped < count) { skipped++; continue; } yield item; } } export function* map(iterable, mapper) { let index = 0; for (const item of iterable) { yield mapper(item, index++); } } export function reduce(iterable, reducer, initialValue) { let acc = initialValue; let index = 0; for (const item of iterable) { acc = reducer(acc, item, index++); } return acc; } export function toArray(iterable) { return Array.from(iterable); } export function forEach(iterable, callback) { let index = 0; for (const item of iterable) { callback(item, index++); } } export function every(iterable, predicate) { let index = 0; for (const item of iterable) { if (!predicate(item, index++)) { return false; } } return true; } export function some(iterable, predicate) { let index = 0; for (const item of iterable) { if (predicate(item, index++)) { return true; } } return false; } export function find(iterable, predicate) { let index = 0; for (const item of iterable) { if (predicate(item, index++)) { return item; } } return undefined; } export function* chunk(iterable, size) { if (size <= 0) { throw new Error(`Chunk size must be positive, received: ${size}`); } let currentChunk = []; for (const item of iterable) { currentChunk.push(item); if (currentChunk.length >= size) { yield currentChunk; currentChunk = []; } } if (currentChunk.length > 0) { yield currentChunk; } } export function* flatten(iterable) { for (const item of iterable) { if (typeof item === 'object' && item !== null && Symbol.iterator in item) { yield* item; } else { yield item; } } } export async function* asyncMap(iterable, mapper) { let index = 0; for await (const item of iterable) { yield await mapper(item, index++); } } export async function* asyncFilter(iterable, predicate) { let index = 0; for await (const item of iterable) { if (await predicate(item, index++)) { yield item; } } } //# sourceMappingURL=lazy-iterators.js.map