swingmobility-utils
Version:
Swing 공통 유틸리티 함수
426 lines (418 loc) • 13.7 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
chunk: () => chunk,
convertDayFormat: () => convertDayFormat,
dateToUnixEpoch: () => dateToUnixEpoch,
epochMillisecondsToDate: () => epochMillisecondsToDate,
formatCurrency: () => formatCurrency,
formatEpochMilliseconds: () => formatEpochMilliseconds,
formatNumber: () => formatNumber,
formatSafeDate: () => formatSafeDate,
getDayIndex: () => getDayIndex,
getDayOfWeek: () => getDayOfWeek,
getDefaultOpenMonth: () => getDefaultOpenMonth,
getKoreanWeekOfMonth: () => getKoreanWeekOfMonth,
getKstDateString: () => getKstDateString,
getNextDayOfWeek: () => getNextDayOfWeek,
getWeekDays: () => getWeekDays,
isDateDisabled: () => isDateDisabled,
isSameDayOfWeek: () => isSameDayOfWeek,
isValidEmail: () => isValidEmail,
isValidPhoneNumber: () => isValidPhoneNumber,
isValidRRN: () => isValidRRN,
isWeekday: () => isWeekday,
isWeekend: () => isWeekend,
maskAccount: () => maskAccount,
maskBirthDate: () => maskBirthDate,
maskEmail: () => maskEmail,
maskName: () => maskName,
maskPhone: () => maskPhone,
maskRRN: () => maskRRN,
maskToSigungu: () => maskToSigungu,
removeDuplicates: () => removeDuplicates,
sortByProperty: () => sortByProperty,
unixEpochToDate: () => unixEpochToDate,
unixEpochToMilliseconds: () => unixEpochToMilliseconds
});
module.exports = __toCommonJS(index_exports);
// src/mask/index.ts
var maskName = (name) => {
if (!name) return "-";
const len = name.length;
if (len === 1) return name;
if (len === 2) return `${name[0]}*`;
if (len === 3) return `${name[0]}*${name[2]}`;
return `${name.slice(0, -2)}**`;
};
var maskBirthDate = (birth) => {
if (!birth) return "-";
if (birth.length === 8 && /^\d{8}$/.test(birth)) {
return `${birth.slice(0, 4)}**${birth.slice(6)}`;
}
if (birth.length === 10 && birth.includes("-")) {
const parts = birth.split("-");
if (parts.length === 3) {
return `${parts[0]}-**-${parts[2]}`;
}
}
return birth;
};
var maskPhone = (phone, hasHyphen = false, showErrorPattern = true) => {
if (!phone) return "-";
let number = String(phone).replace(/\D/g, "");
if (number.length <= 8 || number.length > 12) {
return showErrorPattern ? number : "-";
}
let areaLen = 3;
if (number.startsWith("0")) {
if (number.length === 12) areaLen = 4;
else if (number.length === 11) areaLen = 3;
else if (number.length <= 10) areaLen = 2;
} else {
if (number.length === 12) areaLen = 4;
}
const area = number.slice(0, areaLen);
const remain = number.slice(areaLen);
const last = remain.slice(-4);
let midLen = remain.length - 4;
if (midLen < 3) midLen = 3;
const mid = "*".repeat(midLen);
const masked = hasHyphen ? `${area}-${mid}-${last}` : `${area}${mid}${last}`;
return masked;
};
var maskEmail = (email) => {
if (!email) return "-";
const [local, domain] = email.split("@");
if (!domain) return email;
if (local.length <= 2) return `${local}@${domain}`;
return `${local.slice(0, 2)}${"*".repeat(local.length - 2)}@${domain}`;
};
var maskToSigungu = (address) => {
if (!address) return "-";
const tokens = address.trim().split(/\s+/);
if (tokens.length < 2) return address;
const resultParts = [tokens[0]];
let i = 1;
for (; i < tokens.length; i++) {
if (/(시|군|구)$/.test(tokens[i])) {
resultParts.push(tokens[i]);
} else {
break;
}
}
const maskedParts = tokens.slice(i).map((part) => "*".repeat(part.length));
return resultParts.concat(maskedParts).join(" ");
};
var maskRRN = (rrn) => {
if (!rrn) return "-";
const cleaned = rrn.replace(/\D/g, "");
if (cleaned.length !== 13) return "-";
return `${cleaned.slice(0, 6)}-${cleaned.slice(6, 7)}******`;
};
var maskAccount = (account) => {
if (!account) return "-";
const cleaned = account.replace(/\D/g, "");
if (cleaned.length < 8) return "-";
return `${cleaned.slice(0, 4)}${"*".repeat(cleaned.length - 8)}${cleaned.slice(-4)}`;
};
// src/format/currency.ts
function formatCurrency(amount) {
return new Intl.NumberFormat("ko-KR", {
style: "currency",
currency: "KRW",
currencyDisplay: "symbol"
}).format(amount);
}
// src/format/number.ts
function formatNumber(num) {
return num.toLocaleString("ko-KR");
}
// src/format/date.ts
var DAY_MAPPINGS = {
"ko-short": ["\uC77C", "\uC6D4", "\uD654", "\uC218", "\uBAA9", "\uAE08", "\uD1A0"],
"ko-long": ["\uC77C\uC694\uC77C", "\uC6D4\uC694\uC77C", "\uD654\uC694\uC77C", "\uC218\uC694\uC77C", "\uBAA9\uC694\uC77C", "\uAE08\uC694\uC77C", "\uD1A0\uC694\uC77C"],
"en-short": ["sun", "mon", "tue", "wed", "thu", "fri", "sat"],
"en-short-caps": ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"],
"en-long": ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"],
"en-long-caps": ["SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"]
};
function getDayOfWeek(date, format = "ko-short") {
const dayIndex = date.getDay();
return DAY_MAPPINGS[format][dayIndex];
}
function convertDayFormat(day, targetFormat) {
let foundFormat = null;
let dayIndex = -1;
const formats = Object.keys(DAY_MAPPINGS);
for (const format of formats) {
const days = DAY_MAPPINGS[format];
const index = days.indexOf(day);
if (index !== -1) {
foundFormat = [format, days];
dayIndex = index;
break;
}
}
if (!foundFormat || dayIndex === -1) return null;
return DAY_MAPPINGS[targetFormat][dayIndex];
}
function getDayIndex(day) {
const formats = Object.keys(DAY_MAPPINGS);
for (const format of formats) {
const days = DAY_MAPPINGS[format];
const index = days.indexOf(day);
if (index !== -1) {
return index;
}
}
return null;
}
function getWeekDays(date, startFromSunday = true) {
const result = [];
const currentDate = new Date(date);
const currentDay = currentDate.getDay();
const startDay = startFromSunday ? 0 : 1;
const diff = currentDay - startDay;
const offsetDays = diff < 0 ? diff + 7 : diff;
currentDate.setDate(currentDate.getDate() - offsetDays);
for (let i = 0; i < 7; i++) {
const weekDate = new Date(currentDate);
weekDate.setDate(currentDate.getDate() + i);
result.push(weekDate);
}
return result;
}
function isSameDayOfWeek(date1, date2) {
return date1.getDay() === date2.getDay();
}
function getNextDayOfWeek(targetDay, baseDate = /* @__PURE__ */ new Date(), searchForward = true) {
const targetDayIndex = getDayIndex(targetDay);
if (targetDayIndex === null) {
return null;
}
const result = new Date(baseDate);
const currentDayIndex = result.getDay();
let daysToAdd;
if (searchForward) {
daysToAdd = (targetDayIndex - currentDayIndex + 7) % 7;
if (daysToAdd === 0) daysToAdd = 7;
} else {
daysToAdd = (targetDayIndex - currentDayIndex - 7) % 7;
if (daysToAdd === 0) daysToAdd = -7;
}
result.setDate(result.getDate() + daysToAdd);
return result;
}
function isWeekend(date) {
const day = date.getDay();
return day === 0 || day === 6;
}
function isWeekday(date) {
return !isWeekend(date);
}
function addHours(date, hours) {
const result = new Date(date);
result.setHours(result.getHours() + hours);
return result;
}
function subtractDays(date, days) {
const result = new Date(date);
result.setDate(result.getDate() - days);
return result;
}
function isSameDay(date1, date2) {
return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate();
}
function fromUnixTime(timestamp) {
return new Date(timestamp * 1e3);
}
function isValidDate(date) {
return !isNaN(date.getTime());
}
function formatDate(date, formatStr) {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const pad2 = (num) => {
return num < 10 ? `0${num}` : num.toString();
};
return formatStr.replace(/yyyy/g, year.toString()).replace(/MM/g, pad2(month)).replace(/M/g, month.toString()).replace(/dd/g, pad2(day)).replace(/d/g, day.toString());
}
function getWeekOfMonth(date) {
const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
const dayOfMonth = date.getDate();
const firstDayOfWeek = firstDayOfMonth.getDay();
const daysInFirstWeek = 7 - firstDayOfWeek;
if (dayOfMonth > daysInFirstWeek) {
return Math.ceil((dayOfMonth - daysInFirstWeek) / 7) + 1;
}
return 1;
}
function getKstDateString() {
const now = /* @__PURE__ */ new Date();
const kstTime = addHours(now, 9);
return kstTime.toISOString().split("T")[0];
}
function isDateDisabled(date, startDateStr, endDateStr, today = /* @__PURE__ */ new Date()) {
const start = startDateStr ? new Date(startDateStr) : today;
const end = endDateStr ? new Date(endDateStr) : today;
const endIsToday = isSameDay(end, today);
const isStartSameAsEnd = isSameDay(start, end);
if (isStartSameAsEnd) {
return !isSameDay(date, start);
}
if (endIsToday) {
return !isSameDay(date, today);
}
return date < start || date > end || date < subtractDays(today, 1);
}
function getDefaultOpenMonth(startDateStr, endDateStr, today = /* @__PURE__ */ new Date()) {
const start = startDateStr ? new Date(startDateStr) : today;
const end = endDateStr ? new Date(endDateStr) : today;
if (start < today) return start;
if (end > today) return end;
return today;
}
function getKoreanWeekOfMonth(date) {
const year = date.getFullYear().toString();
const month = (date.getMonth() + 1).toString();
const week = getWeekOfMonth(date);
return `${year}\uB144 ${month}\uC6D4 ${week}\uC8FC\uCC28`;
}
function formatSafeDate(dateValue, formatString) {
if (!dateValue) return "-";
let date;
try {
if (typeof dateValue === "number" || !isNaN(Number(dateValue))) {
const timestamp = Number(dateValue);
date = timestamp > 1e12 ? new Date(timestamp) : fromUnixTime(timestamp);
} else {
date = new Date(dateValue);
}
if (!isValidDate(date)) return "-";
return formatDate(date, formatString);
} catch (error) {
console.error("\uB0A0\uC9DC \uD3EC\uB9F7\uD305 \uC624\uB958:", error);
return "-";
}
}
function dateToUnixEpoch(date) {
return Math.floor(date.getTime() / 1e3);
}
function unixEpochToMilliseconds(epochSeconds) {
return epochSeconds * 1e3;
}
function unixEpochToDate(epochSeconds) {
return new Date(epochSeconds * 1e3);
}
function epochMillisecondsToDate(epochMilliseconds) {
return new Date(epochMilliseconds);
}
function formatEpochMilliseconds(epochMilliseconds, format = "yyyy-MM-dd") {
const date = new Date(epochMilliseconds);
const pad2 = (num) => {
return num < 10 ? `0${num}` : String(num);
};
const year = date.getFullYear();
const month = pad2(date.getMonth() + 1);
const day = pad2(date.getDate());
return format.replace(/yyyy/g, String(year)).replace(/MM/g, month).replace(/dd/g, day);
}
// src/validation/index.ts
function isValidRRN(rrn) {
const cleanRRN = rrn.replace(/-/g, "");
if (!/^\d{13}$/.test(cleanRRN)) {
return false;
}
const year = parseInt(cleanRRN.substring(0, 2));
const month = parseInt(cleanRRN.substring(2, 4));
const day = parseInt(cleanRRN.substring(4, 6));
if (month < 1 || month > 12) return false;
if (day < 1 || day > 31) return false;
const digits = cleanRRN.split("").map((d) => parseInt(d));
const multipliers = [2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < 12; i++) {
sum += digits[i] * multipliers[i];
}
const checksum = (11 - sum % 11) % 10;
return checksum === digits[12];
}
function isValidPhoneNumber(phone) {
const cleanPhone = phone.replace(/-/g, "");
return /^01[016789]\d{7,8}$/.test(cleanPhone);
}
function isValidEmail(email) {
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
// src/array/index.ts
function removeDuplicates(array) {
return [...new Set(array)];
}
function chunk(array, size) {
return Array.from(
{ length: Math.ceil(array.length / size) },
(_, i) => array.slice(i * size, i * size + size)
);
}
function sortByProperty(array, property) {
return [...array].sort(
(a, b) => a[property] > b[property] ? 1 : -1
);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
chunk,
convertDayFormat,
dateToUnixEpoch,
epochMillisecondsToDate,
formatCurrency,
formatEpochMilliseconds,
formatNumber,
formatSafeDate,
getDayIndex,
getDayOfWeek,
getDefaultOpenMonth,
getKoreanWeekOfMonth,
getKstDateString,
getNextDayOfWeek,
getWeekDays,
isDateDisabled,
isSameDayOfWeek,
isValidEmail,
isValidPhoneNumber,
isValidRRN,
isWeekday,
isWeekend,
maskAccount,
maskBirthDate,
maskEmail,
maskName,
maskPhone,
maskRRN,
maskToSigungu,
removeDuplicates,
sortByProperty,
unixEpochToDate,
unixEpochToMilliseconds
});