acupedia-mobile-ui/src/features/content/renderers/helpers/value.ts

47 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

export function asString(value: unknown): string {
if (typeof value === "string") return value;
if (typeof value === "number" || typeof value === "boolean") return String(value);
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
const record = value as Record<string, unknown>;
for (const key of ["label", "point_name", "food_name", "name", "title", "code"]) {
if (typeof record[key] === "string" && (record[key] as string).trim().length > 0) {
return (record[key] as string).trim();
}
}
}
return "";
}
export function asNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
export function asStringArray(value: unknown): string[] {
if (!Array.isArray(value)) return [];
return value
.map((item) => asString(item).trim())
.filter((item) => item.length > 0);
}
export function asRecord(value: unknown): Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
export function asRecordArray(value: unknown): Record<string, unknown>[] {
return Array.isArray(value)
? value.filter(
(item): item is Record<string, unknown> =>
item !== null && typeof item === "object" && !Array.isArray(item),
)
: [];
}
export function humanizeKey(value: string): string {
return value
.replace(/[_-]/g, " ")
.replace(/\b\w/g, (letter) => letter.toUpperCase())
.replace(/(['’‘ʼ])s\b/gi, (match) => match[0] + "s");
}