Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | 3x 3x 3x 3x 3x 18x 37x 4x 18x 18x 3x 15x 15x 21x 21x 21x 135x 37x 98x 18x | export enum AttributeValueType {
Number = "number",
String = "string",
Boolean = "boolean",
}
export interface AttributeDefinition {
name: string;
valueType: AttributeValueType;
defaultValue: unknown
}
interface RawAttributes {
[attr: string]: unknown
}
export interface ParsedAttributes {
[attr: string]: string | number | boolean
}
export class AttributeParser {
constructor(private schema: AttributeDefinition[]) {}
private parseAttribute(attr: AttributeDefinition, rawValue: unknown) {
switch (attr.valueType) {
case AttributeValueType.Boolean:
return !!rawValue;
case AttributeValueType.Number: {
const v = typeof rawValue === "string" ? Number.parseFloat(rawValue) : rawValue;
if (typeof v !== "number" || Number.isNaN(v)) {
throw new Error(`Can't convert "${rawValue}" to number while parsing ${attr.name}.`);
}
return v;
}
case AttributeValueType.String:
return new String(rawValue).toString();
}
}
parse(rawAttributes: RawAttributes): ParsedAttributes {
const parsedAttributes = {};
Iif (!(typeof rawAttributes === "object")) {
throw new Error("There was an error parsing attributes.")
}
for (const attr of this.schema) {
if (attr.name in rawAttributes) {
parsedAttributes[attr.name] = this.parseAttribute(attr, rawAttributes[attr.name]);
} else {
parsedAttributes[attr.name] = attr.defaultValue;
}
}
return parsedAttributes;
}
}
|