UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

90 lines (89 loc) 2.5 kB
/** Is an unknown value an iterable? */ export const isIterable = (value) => typeof value === "object" && !!value && Symbol.iterator in value; /** Flatten one or more iterables. */ export function* flattenItems(items) { if (isIterable(items)) for (const item of items) yield* flattenItems(item); else yield items; } /** * Does an iterable have one or more items. * - Checks `items.size` or `items.length` first, or consumes the iterable and counts its iterations. */ export function hasItems(items) { for (const unused of items) return true; return false; } /** Count the number of items in an iterable. */ export function countItems(items) { let count = 0; for (const unused of items) count++; return count; } /** * Yield a range of numbers from `start` to `end` * - Yields in descending order if `end` is lower than `start` */ export function* getRange(start, end) { if (start <= end) for (let num = start; num <= end; num++) yield num; else for (let num = start; num >= end; num--) yield num; } /** * Apply a limit to an iterable set of items. * - Checks `items.size` or `items.length` first to see if the limit is necessary. */ export function* limitItems(items, limit) { let count = 0; if (count >= limit) return; for (const item of items) { yield item; count++; if (count >= limit) return; } } /** Pick items from an iterable set of items. */ export function* pickItems(items, ...pick) { for (const item of items) if (pick.includes(item)) yield item; } /** Omit items from an iterable set of items. */ export function* omitItems(items, ...omit) { for (const item of items) if (!omit.includes(item)) yield item; } export function reduceItems(items, reducer, initial) { let current = initial; for (const item of items) current = reducer(current, item); return current; } /** Yield chunks of a given size. */ export function* getChunks(items, size) { let chunk = []; for (const item of items) { chunk.push(item); if (chunk.length >= size) { yield chunk; chunk = []; } } if (chunk.length) yield chunk; } /** Merge two or more iterables into a single iterable set. */ export function* mergeItems(...inputs) { for (const input of inputs) yield* input; }