Files
lg-cxdash-front/src/lib/utils.ts

160 lines
5.0 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.

import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function getKeyByValue<
const T extends Record<PropertyKey, string>
>(map: T, value: T[keyof T]) {
const entry = Object.entries(map).find(([, v]) => v === value);
return entry ? (entry[0] as keyof T) : undefined;
}
export function getNumberKeyByValue(
map: Record<number, string>,
value: string
): number | undefined {
const entry = Object.entries(map).find(([, v]) => v === value);
return entry ? Number(entry[0]) : undefined;
}
export function buildUrlWithParams(
targetPath: string,
from: Record<string, string | string[] | undefined>,
extra?: Record<string, string | undefined>,
) {
const qs = new URLSearchParams();
for (const [k, v] of Object.entries(from)) {
if (Array.isArray(v)) v.forEach((val) => qs.append(k, val));
else if (v !== undefined) qs.set(k, v);
}
if (extra) for (const [k, v] of Object.entries(extra)) if (v) qs.set(k, v);
return `${targetPath}${qs.toString() ? `?${qs}` : ""}`;
}
export const downloadFile = (blob: Blob, filename: string) => {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
};
export const downloadBase64File = (base64: string, filename: string) => {
const byteString = atob(base64);
const arrayBuffer = new ArrayBuffer(byteString.length);
const uint8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
uint8Array[i] = byteString.charCodeAt(i);
}
const blob = new Blob([arrayBuffer], {
type:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
downloadFile(blob, filename);
};
export type DateTimeFormatOption =
| "date" // 1-1. 날짜만
| "dateHour" // 1-2. 날짜 + 시
| "dateHourMin" // 1-3. 날짜 + 시 분
| "dateTime"; // 1-4. 날짜 + 시 분 초
/**
* 서버에서 받은 시간(ISO 문자열/Date/number)을 한국시간 기준으로 포맷팅
* - 예: "2025-11-28T03:15:50Z" -> "2025-11-28 12:15:50" (KST)
*/
export const formatKst = (
input: string | number | Date | null | undefined,
opt: DateTimeFormatOption = "dateTime"
): string => {
if (!input) return "";
const d = input instanceof Date ? input : new Date(input);
if (Number.isNaN(d.getTime())) return "";
// UTC -> KST(UTC+9) 변환
const kst = new Date(d.getTime() + 9 * 60 * 60 * 1000);
const pad2 = (n: number) => String(n).padStart(2, "0");
const yyyy = kst.getUTCFullYear();
const MM = pad2(kst.getUTCMonth() + 1);
const dd = pad2(kst.getUTCDate());
const HH = pad2(kst.getUTCHours());
const mm = pad2(kst.getUTCMinutes());
const ss = pad2(kst.getUTCSeconds());
if (opt === "date") return `${yyyy}-${MM}-${dd}`;
if (opt === "dateHour") return `${yyyy}-${MM}-${dd} ${HH}`;
if (opt === "dateHourMin") return `${yyyy}-${MM}-${dd} ${HH}:${mm}`;
return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`;
};
export const isBlank = (v?: string | null) => !v || v.trim().length === 0;
export const norm = (s: string) => s.replace(/\s+/g, "").toLowerCase();
export const asNum = (v: unknown): number | null => typeof v === "number" && Number.isFinite(v) ? v : null;
export const formatNumber = (v: number) =>
Number.isInteger(v) ? v.toLocaleString() : v.toLocaleString(undefined, { maximumFractionDigits: 1 });
/**
* 다양한 형식의 값을 숫자로 파싱합니다.
* - 쉼표, 퍼센트, 유니코드 마이너스 자동 처리
* - null/undefined/빈문자열/"−" 등은 null 반환
* - 유한하지 않은 숫자는 null 반환
*/
export function parseNumber(
value: unknown,
options?: {
allowComma?: boolean; // 기본값: true
allowPercent?: boolean; // 기본값: true
allowMinus?: boolean; // 기본값: true (유니코드 마이너스 포함)
}
): number | null {
const { allowComma = true, allowPercent = true, allowMinus = true } = options ?? {};
if (value === null || value === undefined) return null;
if (typeof value === "number") {
return Number.isFinite(value) ? value : null;
}
if (typeof value === "string") {
let s = value.trim();
if (s === "" || s === "-" || s === "−") return null;
s = s.replaceAll("(", "");
s = s.replaceAll(")", "");
if (allowComma) s = s.replaceAll(",", "");
if (allowPercent) s = s.replaceAll("%", "");
if (allowMinus) s = s.replaceAll("−", "-"); // 유니코드 마이너스 -> ASCII 마이너스
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
return null;
}
export const toNumOrNull = (v: unknown) => {
if (v == null) return null;
if (v === "-" || v === "") return null;
const n = Number(v);
return Number.isFinite(n) ? n : null;
};
export const toNumOr0 = (v: unknown) => {
const n = Number(v);
return Number.isFinite(n) ? n : 0;
};