JSPM

@raju_kar/code-formatter

1.1.3
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 2
  • Score
    100M100P100Q28698F
  • License ISC

Timezone-aware date & currency formatter plus numbers, HTML, slugify, and TTS utilities for Node/React. Uses Intl, moment/moment-timezone, numeral. TypeScript types included.

Package Exports

  • @raju_kar/code-formatter

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, optional moment-timezone)
  • Currency and numbers (via numeral and Intl)
  • 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-timezone

Usage

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., JPY has 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-call locale > preset locale > global locale.

Timezone behavior

  • configureFormatter({ timeZone: 'auto' }): detects each user’s timezone (via moment.tz.guess() if moment-timezone is installed; otherwise via Intl as a fallback). Shows each user their local time.
  • configureFormatter({ timeZone: 'Asia/Kolkata' }): pins all output to a specific zone.
  • No timeZone set: 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 zone
    • relativeTime(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?) — uses Intl.NumberFormat; falls back to numeral
    • numberFormatter(value, pattern='0,0.[00]')
    • percentFormatter(value, decimals=2, input='ratio'|'percent')
    • compactNumberFormatter(value, decimals=1) — 1.5k/3.2m
    • fileSizeFormatter(bytes, decimals=1, si=false) — 10.0 MiB
    • ordinalFormatter(n) — 21st
    • formatBoolean(value, yes='Yes', no='No', empty='-')
  • Text and mapping

    • toSentenceCase(str) — smart tokenization for constants
    • labelTextFormatter(str, maxChar?)
    • specialCharValueFormatter(input) / reverseSpecialCharValueFormatter(str)
    • stripDiacritics(str) — Crème → Creme
    • normalizeUnicode(str, form) — NFC/NFD/NFKC/NFKD
    • slugify(str) — trims, collapses, returns web-friendly slugs
    • collapseWhitespace(str) / capitalize(str) / titleCase(str) / truncateText(str, max?, ellipsis?)
    • fileNameFormatter(str) — safe file names
    • formatTextToSpeech(str) / formatTextToSpeechAbbreviations(str)
  • HTML handling

    • replaceNewLineToLineBreak(str)
    • replaceNewLineToLineBreakSafe(str) — converts only text parts, preserves HTML
    • replaceNewLineToLineBreakSmart(str) — auto-detects HTML
    • replaceNewLineToLineBreakForTables(str) — protects table layout
    • stripHtmlTags(str) — strips tags, script/style
    • sanitizeHtmlBasic(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' }) (install moment-timezone for best results). Then dateFormatter(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' }. Use formatInTimeZone for per-call overrides.
  • Can I format currency with ISO codes and locales?

    • Yes: currencyFormatter(1234.56, 'EUR', 'de-DE'). It uses Intl.NumberFormat and falls back to numeral.
  • 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.