Page MenuHomeSealhub

list.ts
No OneTemporary

import { is, predicates } from "@sealcode/ts-predicates";
import { MaybePromise } from "../utils/util-types.js";
import { ComponentArgument } from "./component-argument.js";
import { ContainerArgument } from "./container-argument.js";
import { JDDContext } from "../jdd-context.js";
export class List<
ParsedType,
T extends ComponentArgument<ParsedType, unknown, unknown>
> extends ContainerArgument<ParsedType[], unknown, unknown> {
constructor(
public item_type: ComponentArgument<ParsedType, unknown, unknown>,
public example_count: number | null = null
) {
super();
item_type.parent_argument = this;
}
getTypeName() {
return "list";
}
getEmptyValue() {
return [];
}
getSubArgument([key, ...rest]: string[], value: unknown[]) {
const parsed_key = parseInt(key);
if (isNaN(parsed_key)) {
return <const>[null, [] as string[], null];
}
return <const>[this.item_type, rest, value[parsed_key]];
}
getExampleCount() {
if (this.example_count === null) {
return Math.floor(Math.random() * 5);
} else {
return this.example_count;
}
}
async getExampleValue(context: JDDContext): Promise<ParsedType[]> {
if (this.example_values.length) {
return super.getExampleValue(context);
} else {
const count = this.getExampleCount();
const result = [] as Array<MaybePromise<ParsedType>>;
for (let i = 0; i < count; i++) {
result.push(
this.item_type.getExampleValue(
context
) as Promise<ParsedType>
);
}
return await Promise.all(result);
}
}
countWords(value: Array<ParsedType>): number {
return value.reduce(
(acc, item) => acc + this.item_type.countWords(item),
0
);
}
async processAllSubarguments(
_context: JDDContext,
values: unknown,
processing_function: (
argument: ComponentArgument<unknown>,
value: unknown
) => Promise<unknown>
): Promise<T[] | null> {
if (!values) {
return [];
}
if (
!is(values, predicates.array(predicates.object)) &&
!is(values, predicates.object)
) {
throw new Error(`Not a list or object: ${values as string}`);
}
const values_array = Array.isArray(values)
? values
: Object.values(values);
let array_result = (await Promise.all(
values_array.map(async (value) => {
const result = await processing_function(this.item_type, value);
return result;
})
)) as Array<T | T[] | null>;
if (this.item_type.getTypeName() != "list") {
array_result = array_result.flat() as T[];
}
const result = array_result.filter((e) => e !== null) as T[];
return result;
}
}

File Metadata

Mime Type
text/x-java
Expires
Wed, May 7, 19:46 (1 d, 4 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
630332
Default Alt Text
list.ts (2 KB)

Event Timeline