47 lines
1.1 KiB
TypeScript
47 lines
1.1 KiB
TypeScript
import type { Market } from "@/src/domain/types";
|
||
|
||
export type ParsedStockRef = { code: string; market: Market };
|
||
|
||
export function parseStockRef(raw: string): ParsedStockRef | null {
|
||
const s = raw.trim();
|
||
if (!s) return null;
|
||
|
||
// allow forms:
|
||
// 600519
|
||
// SH:600519
|
||
// SZ:000001
|
||
// BJ:xxxxxx
|
||
const m = s.match(/^(?:(SH|SZ|BJ)[::])?(\d{6})$/i);
|
||
if (!m) return null;
|
||
|
||
const market = (m[1]?.toUpperCase() as Market | undefined) ?? guessMarket(m[2]!);
|
||
return { market, code: m[2]! };
|
||
}
|
||
|
||
function guessMarket(code: string): Market {
|
||
if (code.startsWith("6")) return "SH";
|
||
if (code.startsWith("8") || code.startsWith("9")) return "BJ";
|
||
return "SZ";
|
||
}
|
||
|
||
export function normalizeImportedPool(text: string): ParsedStockRef[] {
|
||
const lines = text
|
||
.split(/\r?\n/)
|
||
.map((l) => l.trim())
|
||
.filter(Boolean);
|
||
|
||
const out: ParsedStockRef[] = [];
|
||
const seen = new Set<string>();
|
||
|
||
for (const line of lines) {
|
||
const ref = parseStockRef(line);
|
||
if (!ref) continue;
|
||
const key = `${ref.market}:${ref.code}`;
|
||
if (seen.has(key)) continue;
|
||
seen.add(key);
|
||
out.push(ref);
|
||
}
|
||
|
||
return out;
|
||
}
|