82 lines
2.0 KiB
JavaScript
82 lines
2.0 KiB
JavaScript
const MAX_REGION_LENGTH = 3;
|
|
|
|
function sanitizeSegment(value) {
|
|
if (typeof value !== "string") {
|
|
return "";
|
|
}
|
|
const trimmed = value.trim();
|
|
if (!trimmed || trimmed === "全部") {
|
|
return "";
|
|
}
|
|
return trimmed;
|
|
}
|
|
|
|
function normalizeRegionArray(region) {
|
|
if (!Array.isArray(region)) {
|
|
return [];
|
|
}
|
|
const sanitized = region.map(sanitizeSegment);
|
|
const hasValue = sanitized.some(Boolean);
|
|
if (!hasValue) {
|
|
return [];
|
|
}
|
|
const normalized = sanitized.slice(0, MAX_REGION_LENGTH);
|
|
while (normalized.length < MAX_REGION_LENGTH) {
|
|
normalized.push("");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function deriveRegionFromParts(parts = {}) {
|
|
const segments = [];
|
|
if (parts.province) {
|
|
segments.push(parts.province);
|
|
}
|
|
if (parts.city) {
|
|
segments.push(parts.city);
|
|
}
|
|
if (parts.district && parts.district !== parts.city) {
|
|
segments.push(parts.district);
|
|
}
|
|
if (!segments.length && parts.city) {
|
|
segments.push(parts.city);
|
|
}
|
|
return normalizeRegionArray(segments);
|
|
}
|
|
|
|
function getRegionParts(region, fallback = {}) {
|
|
const normalized = normalizeRegionArray(region);
|
|
if (!normalized.length) {
|
|
return {
|
|
province: sanitizeSegment(fallback.province),
|
|
city: sanitizeSegment(fallback.city),
|
|
district: sanitizeSegment(fallback.district)
|
|
};
|
|
}
|
|
const [province = "", city = "", district = ""] = normalized;
|
|
return {
|
|
province: province || sanitizeSegment(fallback.province),
|
|
city: city || province || sanitizeSegment(fallback.city),
|
|
district: district || sanitizeSegment(fallback.district)
|
|
};
|
|
}
|
|
|
|
function formatRegionDisplay(region, fallbackList = []) {
|
|
const normalized = normalizeRegionArray(region);
|
|
const source = normalized.length ? normalized : fallbackList;
|
|
if (!source || !source.length) {
|
|
return "";
|
|
}
|
|
return source
|
|
.filter(sanitizeSegment)
|
|
.filter((item, index, arr) => arr.indexOf(item) === index)
|
|
.join(" · ");
|
|
}
|
|
|
|
module.exports = {
|
|
normalizeRegionArray,
|
|
deriveRegionFromParts,
|
|
getRegionParts,
|
|
formatRegionDisplay
|
|
};
|