@raju_kar/code-formatter
v1.1.3
Published
Timezone-aware date & currency formatter plus numbers, HTML, slugify, and TTS utilities for Node/React. Uses Intl, moment/moment-timezone, numeral. TypeScript types included.
Maintainers
Readme
code-formatter: Timezone-aware Date & Currency Formatter for Node/React
A compact, developer-friendly toolkit for everyday formatting in real apps:
- Dates and timezones (via
moment, optionalmoment-timezone) - Currency and numbers (via
numeralandIntl) - Text casing and utilities (slugify/diacritics/unicode/whitespace)
- HTML-safe newline handling and sanitizing
- Special-character mapping helpers
- Identity and list helpers
Install
npm i code-formatter moment numeral
# Optional (recommended for named time zones like Asia/Kolkata):
npm i moment-timezoneUsage
import {
configureFormatter,
dateFormatter,
formatInTimeZone,
currencyFormatter,
numberFormatter,
toSentenceCase,
slugify,
} from 'code-formatter';
// 1) Configure once (anywhere during app bootstrap)
// Show each user their OWN local time using auto timezone detection
configureFormatter({ locale: 'en-US', timeZone: 'auto' });
// Or force a single canonical zone everywhere (e.g., UTC or IST)
// configureFormatter({ timeZone: 'UTC' });
// configureFormatter({ timeZone: 'Asia/Kolkata' });
// Optional: define special char mappings (shown as example)
configureFormatter({
productCharMapper: { '__ia_char_01': 'α' },
reverseProductCharMapper: { 'α': '__ia_char_01' },
});
// 2) Time and Date
const ts = '2024-08-02T06:31:00Z';
console.log(dateFormatter(ts, 'YYYY-MM-DD hh:mm a z')); // user local (auto)
console.log(formatInTimeZone(ts, 'YYYY-MM-DD hh:mm a z', 'Asia/Kolkata'));
console.log(formatInTimeZone(ts, 'YYYY-MM-DD hh:mm a z', 'America/New_York'));
// 3) Money and numbers
console.log(currencyFormatter(1234.56, 'USD')); // $1,234.56
console.log(currencyFormatter(1234.56, 'EUR', 'de-DE')); // 1.234,56 €
console.log(numberFormatter(1234567.891, '0,0.00'));
// 4) Text
console.log(toSentenceCase('API_GET_USER_ID')); // "Api get user id"
console.log(slugify(' Hello, World! ')); // "hello-world"Currency presets
- Built-in presets for common ISO currencies set sensible locales and fraction digits (e.g.,
JPYhas 0 decimals). - Override or batch update:
import { setCurrencyPreset, setCurrencyPresets } from 'code-formatter';
setCurrencyPreset('JPY', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
setCurrencyPresets({ INR: { locale: 'en-IN' } });currencyFormatter(value, iso='USD', locale?)will use: per-calllocale> presetlocale> globallocale.
Timezone behavior
configureFormatter({ timeZone: 'auto' }): detects each user’s timezone (viamoment.tz.guess()ifmoment-timezoneis installed; otherwise viaIntlas a fallback). Shows each user their local time.configureFormatter({ timeZone: 'Asia/Kolkata' }): pins all output to a specific zone.- No
timeZoneset: UTC is used by default for consistency.
API (selected)
Configuration
configureFormatter({ productCharMapper?, reverseProductCharMapper?, locale?, timeZone? })getFormatterConfig()setCurrencyPreset(iso, options)/setCurrencyPresets(map)/getCurrencyPresets()
Dates
dateFormatter(date, format)— honors global timezone (auto/specific/UTC)formatInTimeZone(date, format, timeZone?)— render in any IANA zonerelativeTime(date)— "a minute ago"durationHumanize(ms, withSuffix?)— "an hour"dateRangeFormatter(start, end, format?)formatDate(timestamp)— Today/Yesterday/DD/MM/YYYY
Money and numbers
currencyFormatter(value, iso='USD', locale?)— usesIntl.NumberFormat; falls back tonumeralnumberFormatter(value, pattern='0,0.[00]')percentFormatter(value, decimals=2, input='ratio'|'percent')compactNumberFormatter(value, decimals=1)— 1.5k/3.2mfileSizeFormatter(bytes, decimals=1, si=false)— 10.0 MiBordinalFormatter(n)— 21stformatBoolean(value, yes='Yes', no='No', empty='-')
Text and mapping
toSentenceCase(str)— smart tokenization for constantslabelTextFormatter(str, maxChar?)specialCharValueFormatter(input)/reverseSpecialCharValueFormatter(str)stripDiacritics(str)— Crème → CremenormalizeUnicode(str, form)— NFC/NFD/NFKC/NFKDslugify(str)— trims, collapses, returns web-friendly slugscollapseWhitespace(str)/capitalize(str)/titleCase(str)/truncateText(str, max?, ellipsis?)fileNameFormatter(str)— safe file namesformatTextToSpeech(str)/formatTextToSpeechAbbreviations(str)
HTML handling
replaceNewLineToLineBreak(str)replaceNewLineToLineBreakSafe(str)— converts only text parts, preserves HTMLreplaceNewLineToLineBreakSmart(str)— auto-detects HTMLreplaceNewLineToLineBreakForTables(str)— protects table layoutstripHtmlTags(str)— strips tags, script/stylesanitizeHtmlBasic(str, allowedTags?)— keeps safe tags only
Identity & lists
initialsFromName(name, maxLetters=2)maskEmail(email)/maskPhone(phone)listFormatter(items, locale?, type?, style?)transformDataToSelectOptionsLabelFormatted(data)—{ label, value }[]with mapped labels
ESM / CJS
- ESM:
import { dateFormatter } from 'code-formatter' - CJS:
const { dateFormatter } = require('code-formatter')
TypeScript
Types are bundled via index.d.ts and cover all public APIs, including configuration and currency presets.
FAQ
How do I show the user’s local time?
configureFormatter({ timeZone: 'auto' })(installmoment-timezonefor best results). ThendateFormatter(date, 'YYYY-MM-DD hh:mm a z').
How do I force one global timezone (e.g., UTC/IST)?
configureFormatter({ timeZone: 'UTC' })or{ timeZone: 'Asia/Kolkata' }. UseformatInTimeZonefor per-call overrides.
Can I format currency with ISO codes and locales?
- Yes:
currencyFormatter(1234.56, 'EUR', 'de-DE'). It usesIntl.NumberFormatand falls back tonumeral.
- Yes:
Does this work in React and Node?
- Yes. Dual CJS/ESM exports; tested with React/Vite and Node; TypeScript types included.
Notes
- For accurate named timezones and auto-detection, add
moment-timezone. - The library is framework-agnostic and tested in Node and a React/Vite app.
- Published package is minimal:
index.js,index.mjs,index.d.ts,README.md.
