CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sugar

A comprehensive JavaScript utility library for working with native objects that extends Array, Date, Function, Number, Object, RegExp, and String with powerful methods.

Pending
Overview
Eval results
Files

localization.mddocs/

Localization Module

Comprehensive internationalization system providing date and number formatting, locale management, and multilingual support with 18 built-in locales.

Core Imports

// Import Sugar namespace
import Sugar from "sugar";
// Locale methods available via Sugar.Date namespace

CommonJS:

const Sugar = require("sugar");
// Access locale methods via Date namespace
Sugar.Date.setLocale('fr');
Sugar.Date.getLocale();

Capabilities

Locale Management

Core functions for managing and configuring locales in the Sugar environment.

Add Locale

Registers a new custom locale or updates an existing one with specific formatting rules.

/**
 * Registers a new custom locale or updates an existing one
 * @param localeCode - ISO language code for the locale
 * @param def - Locale definition object with formatting rules
 */
function addLocale(localeCode: string, def: LocaleDefinition): void;

Usage Example:

import Sugar from "sugar";

// Add a custom locale
Sugar.Date.addLocale('custom', {
  'months': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
             'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  'weekdays': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  'numerals': ['zero', 'one', 'two', 'three', 'four', 'five'],
  'tokens': ['the', 'of', 'a'],
  'short': '{Month} {d}',
  'medium': '{Month} {d}, {yyyy}',
  'long': '{Weekday} {Month} {d}, {yyyy}',
  'full': '{Weekday}, {Month} {d}, {yyyy}',
  'stamp': '{Weekday} {Month} {d} {yyyy} {H}:{mm}:{ss}',
  'time': '{H}:{mm}',
  'past': '{num} {unit} ago',
  'future': 'in {num} {unit}',
  'duration': '{num} {unit}',
  'modifiers': [
    { 'name': 'day', 'src': 'yesterday', 'value': -1 },
    { 'name': 'day', 'src': 'today', 'value': 0 },
    { 'name': 'day', 'src': 'tomorrow', 'value': 1 }
  ]
});

Set Locale

Sets the active locale for date parsing and formatting operations.

/**
 * Sets the active locale for date parsing and formatting operations
 * @param localeCode - ISO language code to set as active
 */
function setLocale(localeCode: string): void;

Usage Example:

import Sugar from "sugar";

// Set German locale
Sugar.Date.setLocale('de');
const date = Sugar.Date.create('15. März 2023');
Sugar.Date.format(date, 'full'); // "Mittwoch, 15. März 2023"

// Switch to French locale
Sugar.Date.setLocale('fr');
Sugar.Date.format(date, 'full'); // "mercredi 15 mars 2023"

Get Locale

Retrieves a specific locale object or the currently active locale.

/**
 * Retrieves a specific locale object or the currently active locale
 * @param localeCode - ISO language code (optional, defaults to current locale)
 * @returns Locale object with formatting methods and properties
 */
function getLocale(localeCode?: string): Locale;

Usage Example:

import Sugar from "sugar";

Sugar.Date.setLocale('ja');
const currentLocale = Sugar.Date.getLocale(); // Japanese locale object
const frenchLocale = Sugar.Date.getLocale('fr'); // French locale object

// Access locale methods
currentLocale.getMonthName(0); // "1月" (January in Japanese)
frenchLocale.getMonthName(0);  // "janvier"

Get All Locale Codes

Returns an array of all available locale codes.

/**
 * Returns an array of all available locale codes
 * @returns Array of ISO language codes for all registered locales
 */
function getAllLocaleCodes(): string[];

Usage Example:

import Sugar from "sugar";

const codes = Sugar.Date.getAllLocaleCodes();
// Returns: ['ca', 'da', 'de', 'es', 'fi', 'fr', 'it', 'ja', 'ko', 'nl', 'no', 'pl', 'pt', 'ru', 'sv', 'zh-CN', 'zh-TW']

// Use for building locale selection UI
codes.forEach(code => {
  console.log(`Available locale: ${code}`);
});

Get All Locales

Returns an object containing all registered locale objects.

/**
 * Returns an object containing all registered locale objects
 * @returns Object mapping locale codes to their locale objects
 */
function getAllLocales(): { [localeCode: string]: Locale };

Usage Example:

import Sugar from "sugar";

const allLocales = Sugar.Date.getAllLocales();
const germanLocale = allLocales.de;
const japaneseLocale = allLocales.ja;

// Access properties of specific locales
Object.keys(allLocales).forEach(code => {
  const locale = allLocales[code];
  console.log(`${code}: ${locale.getMonthName(0)}`);
});

Remove Locale

Removes a custom locale from the system (built-in locales cannot be removed).

/**
 * Removes a custom locale from the system
 * @param localeCode - ISO language code of locale to remove
 */
function removeLocale(localeCode: string): void;

Usage Example:

import Sugar from "sugar";

// Add a custom locale
Sugar.Date.addLocale('test', { /* locale definition */ });

// Later remove it
Sugar.Date.removeLocale('test');

// Note: Built-in locales cannot be removed
// Sugar.Date.removeLocale('en'); // This would have no effect

Built-in Locales

Sugar includes 18 pre-configured locales with complete date and number formatting support.

Available Locales

/**
 * Built-in locale codes available in Sugar
 */
type BuiltInLocaleCodes = 
  | 'ca'     // Catalan
  | 'da'     // Danish  
  | 'de'     // German
  | 'es'     // Spanish
  | 'fi'     // Finnish
  | 'fr'     // French
  | 'it'     // Italian
  | 'ja'     // Japanese
  | 'ko'     // Korean
  | 'nl'     // Dutch
  | 'no'     // Norwegian
  | 'pl'     // Polish
  | 'pt'     // Portuguese
  | 'ru'     // Russian
  | 'sv'     // Swedish
  | 'zh-CN'  // Chinese (Simplified)
  | 'zh-TW'; // Chinese (Traditional)

Usage Example:

import Sugar from "sugar";

// Demonstrate different locales
const date = Sugar.Date.create('March 15, 2023');

Sugar.Date.setLocale('de');
Sugar.Date.format(date, 'long'); // "Mittwoch, 15. März 2023"

Sugar.Date.setLocale('fr'); 
Sugar.Date.format(date, 'long'); // "mercredi 15 mars 2023"

Sugar.Date.setLocale('ja');
Sugar.Date.format(date, 'long'); // "2023年3月15日水曜日"

Sugar.Date.setLocale('zh-CN');
Sugar.Date.format(date, 'long'); // "2023年3月15日星期三"

Locale Interface

Each locale object provides methods for accessing localized formatting information.

Add Format

Adds a custom date format pattern to the locale.

/**
 * Adds a custom date format pattern to the locale
 * @param src - Format pattern string using Sugar tokens
 * @param to - Array of alternative format strings (optional)
 */
addFormat(src: string, to?: string[]): void;

Usage Example:

import Sugar from "sugar";

const locale = Sugar.Date.getLocale('en');
locale.addFormat('{dd}/{MM}/{yyyy}', ['DD/MM/YYYY']);
locale.addFormat('{Weekday} the {do}', ['dddd the Do']);

Get Duration

Formats a duration in milliseconds according to locale rules.

/**
 * Formats a duration in milliseconds according to locale rules
 * @param ms - Duration in milliseconds
 * @returns Localized duration string
 */
getDuration(ms: number): string;

Usage Example:

import Sugar from "sugar";

Sugar.Date.setLocale('en');
const enLocale = Sugar.Date.getLocale();
enLocale.getDuration(3661000); // "1 hour"

Sugar.Date.setLocale('de');  
const deLocale = Sugar.Date.getLocale();
deLocale.getDuration(3661000); // "1 Stunde"

Sugar.Date.setLocale('fr');
const frLocale = Sugar.Date.getLocale();
frLocale.getDuration(3661000); // "1 heure"

Get First Day Of Week

Returns the first day of the week for the locale (0 = Sunday, 1 = Monday, etc.).

/**
 * Returns the first day of the week for the locale
 * @returns Number representing first day (0 = Sunday, 1 = Monday, etc.)
 */
getFirstDayOfWeek(): number;

Usage Example:

import Sugar from "sugar";

const usLocale = Sugar.Date.getLocale('en');
usLocale.getFirstDayOfWeek(); // 0 (Sunday)

const germanLocale = Sugar.Date.getLocale('de');
germanLocale.getFirstDayOfWeek(); // 1 (Monday)

const frenchLocale = Sugar.Date.getLocale('fr');
frenchLocale.getFirstDayOfWeek(); // 1 (Monday)

Get First Day Of Week Year

Returns the first day of the week year for ISO week calculations.

/**
 * Returns the first day of the week year for ISO week calculations
 * @returns Number representing first day of week year
 */
getFirstDayOfWeekYear(): number;

Get Month Name

Returns the localized name of a month.

/**
 * Returns the localized name of a month
 * @param n - Month number (0-11, where 0 = January)
 * @returns Localized month name
 */
getMonthName(n: number): string;

Usage Example:

import Sugar from "sugar";

const frenchLocale = Sugar.Date.getLocale('fr');
frenchLocale.getMonthName(0);  // "janvier"
frenchLocale.getMonthName(11); // "décembre"

const germanLocale = Sugar.Date.getLocale('de');
germanLocale.getMonthName(2);  // "März"

const japaneseLocale = Sugar.Date.getLocale('ja');
japaneseLocale.getMonthName(5); // "6月"

Get Weekday Name

Returns the localized name of a weekday.

/**
 * Returns the localized name of a weekday
 * @param n - Weekday number (0-6, where 0 = Sunday)
 * @returns Localized weekday name
 */
getWeekdayName(n: number): string;

Usage Example:

import Sugar from "sugar";

const spanishLocale = Sugar.Date.getLocale('es');
spanishLocale.getWeekdayName(0); // "domingo"
spanishLocale.getWeekdayName(1); // "lunes"

const koreanLocale = Sugar.Date.getLocale('ko');
koreanLocale.getWeekdayName(6); // "토요일"

const dutchLocale = Sugar.Date.getLocale('nl');
dutchLocale.getWeekdayName(3); // "woensdag"

Types

/**
 * Locale interface providing localization methods and properties
 */
interface Locale {
  /**
   * Adds a custom date format pattern to the locale
   */
  addFormat(src: string, to?: string[]): void;
  
  /**
   * Formats a duration in milliseconds according to locale rules
   */
  getDuration(ms: number): string;
  
  /**
   * Returns the first day of the week for the locale
   */
  getFirstDayOfWeek(): number;
  
  /**
   * Returns the first day of the week year for ISO week calculations
   */
  getFirstDayOfWeekYear(): number;
  
  /**
   * Returns the localized name of a month
   */
  getMonthName(n: number): string;
  
  /**
   * Returns the localized name of a weekday
   */
  getWeekdayName(n: number): string;
}

/**
 * Locale definition object for creating custom locales
 */
interface LocaleDefinition {
  months?: string[];
  weekdays?: string[];
  numerals?: string[];
  tokens?: string[];
  short?: string;
  medium?: string;
  long?: string;
  full?: string;
  stamp?: string;
  time?: string;
  past?: string;
  future?: string;
  duration?: string;
  modifiers?: Array<{
    name: string;
    src: string;
    value: number;
  }>;
  parse?: string[];
  timeParse?: string[];
  timeFrontParse?: string[];
}

/**
 * Built-in locale codes available in Sugar
 */
type BuiltInLocaleCodes = 
  | 'ca' | 'da' | 'de' | 'es' | 'fi' | 'fr' | 'it' | 'ja' 
  | 'ko' | 'nl' | 'no' | 'pl' | 'pt' | 'ru' | 'sv' 
  | 'zh-CN' | 'zh-TW';

Install with Tessl CLI

npx tessl i tessl/npm-sugar

docs

array.md

date.md

function.md

index.md

localization.md

number.md

object.md

range.md

regexp.md

string.md

tile.json