Skip to content

Commit

Permalink
feat(element): mapIterable, mapObject directives
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Feb 15, 2023
1 parent be7c12f commit 8958655
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
58 changes: 58 additions & 0 deletions ui/element/src/directives/map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* Returns an iterable containing the result of calling `f(value)` on each value in `items`.
*
* @example
*
* ```ts
* render() {
* return html`
* <ul>
* ${mapIterable(this, items, (i) => html`<li>${i}</li>`, 'loading...')}
* </ul>
* `;
* }
* ```
*/
export function* mapIterable<T>(
_this: unknown,
items: Iterable<T> | undefined,
f: (value: T) => unknown,
loading?: unknown,
): unknown {
if (items === undefined) {
return loading;
}
for (const value of items) {
yield f.call(_this, value);
}
}

/**
* Returns an iterable containing the result of calling `f(value)` on each value in `items`.
*
* @example
*
* ```ts
* render() {
* return html`
* <ul>
* ${mapObject(this, items, (i) => html`<li>${i}</li>`, 'loading...')}
* </ul>
* `;
* }
* ```
*/
export function* mapObject<T>(
_this: unknown,
items: Record<string, T> | undefined | null,
f: (value: T, key: string) => unknown,
loading?: unknown,
): unknown {
if (items == null) {
return loading;
}
for (const key in items) {
if (!Object.prototype.hasOwnProperty.call(items, key)) continue;
yield f.call(_this, items[key], key);
}
}
2 changes: 2 additions & 0 deletions ui/element/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ export * from './mixins/direction.js';
export * from './mixins/logging.js';
export * from './mixins/signal.js';

export * from './directives/map.js';

export * from './lit.js';

globalAlwatr.registeredList.push({
Expand Down

0 comments on commit 8958655

Please sign in to comment.