UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

44 lines (43 loc) 1.51 kB
import { getDictionaryItems } from "./dictionary.js"; import { getProps } from "./object.js"; export function* mapItems(items, transform, ...args) { for (const item of items) yield transform(item, ...args); } export function mapArray(arr, transform, ...args) { return Array.from(mapItems(arr, transform, ...args)); } export function mapObject(obj, transform, ...args) { return Object.fromEntries(mapEntries(getProps(obj), transform, ...args)); } export function mapDictionary(dictionary, transform, ...args) { return Object.fromEntries(mapEntries(getDictionaryItems(dictionary), transform, ...args)); } /** Modify the values of a set of entries using a transform. */ export function* mapEntries(entries, transform, ...args) { for (const [k, v] of entries) yield [k, transform(v, ...args)]; } export function transformObject(input, transforms, ...args) { let changed = false; const output = { ...input }; for (const [k, t] of getProps(transforms)) { if (t) { const i = input[k]; const o = t(i, ...args); if (t === undefined) { delete output[k]; } else { output[k] = o; if (!changed && i !== o) changed = true; } } } return changed ? output : input; } export async function* mapSequence(sequence, transform, ...args) { for await (const item of sequence) yield transform(item, ...args); }