UNPKG

dff-util

Version:

DesignForFeature Utilities

254 lines (253 loc) 8.96 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CurrencyConvert = exports.LangCountryCode = exports.LangText = exports.TimeAgo = exports.DateAndTime = exports.DateTime12HrFormat = exports.DateTime24HrFormat = exports.TruncateText = exports.AppUUID4 = exports.AppAddDays = exports.AppDaysBack = exports.AppCode = exports.AppCodeByType = exports.AppUniqueCode = exports.AppRandomString = void 0; exports.EncodeBase64 = EncodeBase64; exports.DecodeBase64 = DecodeBase64; exports.EncodeURL = EncodeURL; exports.DecodeURL = DecodeURL; exports.SafeEncode = SafeEncode; exports.SafeDecode = SafeDecode; const randomstring_1 = require("randomstring"); const reg_exr_1 = require("./reg-exr"); const countries_1 = require("./countries"); const languages_1 = require("./languages"); const const_value_1 = require("./const-value"); const AppRandomString = (length, charset) => { return (0, randomstring_1.generate)({ length: length, charset: charset }); }; exports.AppRandomString = AppRandomString; let uniqueId = 0; const AppUniqueCode = () => { let time = new Date().getTime(); if (uniqueId == time) { while (new Date().getTime() < 1 + time) { } time = new Date().getTime(); } uniqueId = time; return time.toString(36).toUpperCase(); }; exports.AppUniqueCode = AppUniqueCode; const AppCodeByType = (name, type = null) => { let str = ""; if (type) { str = type + "_" + name; } else { str = name + "_" + (0, exports.AppUniqueCode)(); } str = str.replace(reg_exr_1.RegExp.NON_ALPHA_NUMERIC, "_"); str = str.replace(/\s/g, "_"); str = str.substr(0, 128); return str.toUpperCase(); }; exports.AppCodeByType = AppCodeByType; const AppCode = (name) => { if (name == null) return null; let str = ""; str = name.trim(); str = str.replace(reg_exr_1.RegExp.NON_ALPHA_NUMERIC, "_"); str = str.replace(/\s/g, "_"); return str.toUpperCase(); }; exports.AppCode = AppCode; const AppDaysBack = (date, backValue, isDays = true) => { date = new Date(date); if (isDays) { date.setDate(date.getDate() - backValue); } else { date.setMilliseconds(date.getMilliseconds() - backValue); } date = new Date(date.getFullYear(), date.getMonth(), date.getDate()); return date; }; exports.AppDaysBack = AppDaysBack; const AppAddDays = (date, addDays, isDays = true) => { date = new Date(date); if (isDays) { date.setDate(date.getDate() + addDays); } else { date.setMilliseconds(date.getMilliseconds() + addDays); } date = new Date(date.getFullYear(), date.getMonth(), date.getDate()); return date; }; exports.AppAddDays = AppAddDays; const AppUUID4 = () => { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { const r = (Math.random() * 16) | 0; const v = c == "x" ? r : (r & 0x3) | 0x8; return v.toString(16); }); }; exports.AppUUID4 = AppUUID4; const TruncateText = (input, maxLength) => { if ((input === null || input === void 0 ? void 0 : input.length) > maxLength) { return input.substring(0, maxLength) + "..."; } return input; }; exports.TruncateText = TruncateText; const DateTime24HrFormat = (time) => { const [timeStr, modifier] = time.split(" "); let [hours, minutes] = timeStr.split(":").map(Number); if (modifier === "AM") { if (hours === 12) hours = 0; } else if (modifier === "PM") { if (hours !== 12) hours += 12; } return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:00`; }; exports.DateTime24HrFormat = DateTime24HrFormat; const DateTime12HrFormat = (timestamp, showDate = true, showTime) => { const newDate = new Date(timestamp); const months = const_value_1.ConstValue.MonthNames; const day = String(newDate.getDate()).padStart(2, "0"); const month = months[newDate.getMonth()]; const year = newDate.getFullYear(); let hours = newDate.getHours(); const minutes = String(newDate.getMinutes()).padStart(2, "0"); const ampm = hours >= 12 ? "PM" : "AM"; hours = hours % 12; hours = hours ? hours : 12; const date = showDate ? `${day} ${month} ${year}` : ""; const time = showTime ? `${hours}:${minutes} ${ampm}` : ""; return `${date} ${time}`; }; exports.DateTime12HrFormat = DateTime12HrFormat; const DateAndTime = (dateString, timeString) => { if (!dateString) return null; const validTimeString = timeString || "00:00:00"; const combined = new Date(`${dateString}T${validTimeString}Z`); return isNaN(combined.getTime()) ? null : combined; }; exports.DateAndTime = DateAndTime; const TimeAgo = (date) => { const now = new Date().getTime(); const diff = now - new Date(date).getTime(); const minutes = Math.floor(diff / 60000); const hours = Math.floor(diff / 3600000); const days = Math.floor(diff / 86400000); if (days > 1) return `${days} days ago`; if (days === 1) return "1 day ago"; if (hours > 1) return `${hours} hours ago`; if (hours === 1) return "1 hour ago"; if (minutes > 1) return `${minutes} minutes ago`; if (minutes === 1) return "1 minute ago"; return "Just now"; }; exports.TimeAgo = TimeAgo; const LangText = (data, source, target) => __awaiter(void 0, void 0, void 0, function* () { if (!data || !source || !target) { throw new Error("Invalid input: data, source, or target is missing"); } const src = source.split("-")[0]; // e.g., "en-US" -> "en" const tgt = target.split("-")[0]; // e.g., "te-IN" -> "te" if (!/^[a-zA-Z]{2}$/.test(src) || !/^[a-zA-Z]{2}$/.test(tgt)) { throw new Error("Invalid language code format"); } const encodedData = encodeURIComponent(data); const url = `https://lingva.ml/api/v1/${src}/${tgt}/${encodedData}`; const res = yield fetch(url, { method: "GET", }); if (!res.ok) { throw new Error(`Translation failed: ${res.status} ${res.statusText}`); } const json = yield res.json(); if (json.error) { throw new Error(`API error: ${json.error}`); } return json.translation || ""; }); exports.LangText = LangText; const LangCountryCode = (lang) => { const countryCode = lang.split("-")[1]; const country = countries_1.countries.find((c) => c.code === countryCode) || {}; const language = languages_1.languages.find((l) => l.lang === lang) || {}; return { lang: lang, country: countryCode, name: language.name, locale: language.locale, currencyCode: country.currencyCode, currency: country.currency, telCode: country.telCode, flag: country.flag, dir: language.dir, }; }; exports.LangCountryCode = LangCountryCode; const CurrencyConvert = (from, to) => __awaiter(void 0, void 0, void 0, function* () { if (!from || !to) { throw new Error("Invalid input: from or to is missing"); } if (from === to) { return 1; } try { const url = `https://api.frankfurter.app/latest?from=${from}&to=${to}`; const res = yield fetch(url, { method: "GET", }); if (!res.ok) { throw new Error(`Currency conversion failed: ${res.status} ${res.statusText}`); } const json = yield res.json(); return json.rates[to]; } catch (error) { throw new Error(`Currency conversion failed: ${error}`); } }); exports.CurrencyConvert = CurrencyConvert; function EncodeBase64(input) { return btoa(input); } function DecodeBase64(encoded) { return atob(encoded); } function EncodeURL(input) { try { const decoded = decodeURIComponent(input); return encodeURIComponent(decoded); } catch (_a) { return encodeURIComponent(input); } } function DecodeURL(input) { try { return decodeURIComponent(input); } catch (_a) { return input; } } function SafeEncode(input) { return EncodeURL(EncodeBase64(input)); } function SafeDecode(encoded) { return DecodeBase64(DecodeURL(encoded)); }