shelving
Version:
Toolkit for using data in JavaScript.
49 lines (48 loc) • 1.84 kB
JavaScript
import { getDictionaryItems } from "./dictionary.js";
import { getProps } from "./object.js";
/** Modify a set of items using a transform. */
export function* mapItems(items, transform, ...args) {
for (const item of items)
yield transform(item, ...args);
}
/** Modify the items of an array using a transform. */
export function mapArray(arr, transform, ...args) {
return Array.from(mapItems(arr, transform, ...args));
}
/** Modify the _values_ of the props of an object using a transform. */
export function mapProps(obj, transform, ...args) {
return Object.fromEntries(mapEntries(getProps(obj), transform, ...args));
}
/** Modify the _values_ of a dictionary using a transform. */
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 e of entries)
yield [e[0], transform(e, ...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;
}
/** Transform items in a sequence as they are yielded using a (potentially async) transform. */
export async function* mapSequence(sequence, transform, ...args) {
for await (const item of sequence)
yield transform(item, ...args);
}