A comprehensive JavaScript utility library for working with native objects that extends Array, Date, Function, Number, Object, RegExp, and String with powerful methods.
npx @tessl/cli install tessl/npm-sugar@2.0.0Sugar is a comprehensive JavaScript utility library that extends native JavaScript objects (Array, Date, Function, Number, Object, RegExp, String) with powerful methods for common programming tasks. It provides over 600 methods across multiple modules with extensive internationalization support, covering everything from date parsing in 18+ languages to advanced array operations and string manipulations.
npm install sugarSugar can be used in multiple ways depending on your needs:
Complete Sugar with global extension:
import Sugar from "sugar";
// Extends all native prototypes automaticallyModular approach with namespace:
import Sugar from "sugar";
// Use Sugar.Array.map(), Sugar.String.format(), etc.Specific module imports:
import Sugar from "sugar";
const { Array: SugarArray, Date: SugarDate } = Sugar;CommonJS:
const Sugar = require("sugar");With custom configuration:
import Sugar from "sugar";
Sugar.extend({
namespaces: [Array, Object, String], // Only extend these
methods: ['map', 'filter', 'format'], // Only these methods
enhance: false // Disable enhanced mode
});import Sugar from "sugar";
// Array operations
const users = [
{ name: 'Alice', age: 25, active: true },
{ name: 'Bob', age: 30, active: false },
{ name: 'Charlie', age: 35, active: true }
];
// Find active users over 25
const activeUsers = Sugar.Array.filter(users, { active: true })
.filter(user => user.age > 25);
// Date parsing and formatting
const date = Sugar.Date.create('next Friday at 3pm');
const formatted = Sugar.Date.format(date, '{Weekday} {Month} {dd}, {yyyy}');
// String manipulation
const slug = Sugar.String.parameterize('Hello World Example');
// Result: "hello-world-example"
// Number formatting
const price = Sugar.Number.format(1234.56, 2);
// Result: "1,234.56"
// Object operations
const config = Sugar.Object.merge(
{ timeout: 5000, retries: 3 },
{ timeout: 10000, debug: true }
);
// Result: { timeout: 10000, retries: 3, debug: true }Sugar is built around several key architectural patterns:
Comprehensive array manipulation including functional programming utilities, statistical operations, and advanced filtering.
// Key array methods
function map<T,U>(instance: T[], mapFn: (el: T, i: number, arr: T[]) => U): U[];
function filter<T>(instance: T[], search: any): T[];
function find<T>(instance: T[], search: any): T | undefined;
function unique<T>(instance: T[], mapFn?: (el: T) => any): T[];
function groupBy<T,U>(instance: T[], mapFn: (el: T) => U): { [key: string]: T[] };
function sortBy<T,U>(instance: T[], mapFn?: (el: T) => U, desc?: boolean): T[];Advanced date parsing with natural language support, extensive formatting options, and comprehensive internationalization covering 18+ locales.
// Key date methods
function create(d?: any, options?: DateCreateOptions): Date;
function format(instance: Date, format?: string, locale?: string): string;
function relative(instance: Date, locale?: string): string;
function advance(instance: Date, set: any, reset?: boolean): Date;
function isValid(instance: Date): boolean;
function range(start?: any, end?: any): Range;
interface DateCreateOptions {
locale?: string;
past?: boolean;
future?: boolean;
fromUTC?: boolean;
setUTC?: boolean;
}Function utilities for timing control, memoization, and functional programming patterns.
// Key function methods
function debounce(instance: Function, ms?: number): Function;
function throttle(instance: Function, ms?: number): Function;
function delay(instance: Function, ms?: number, ...args: any[]): number;
function memoize(instance: Function, hashFn?: Function): Function;
function once(instance: Function): Function;
function partial(instance: Function, ...args: any[]): Function;Number formatting, mathematical operations, and iteration utilities with locale-aware formatting.
// Key number methods
function format(instance: number, precision?: number): string;
function abbr(instance: number, precision?: number): string;
function bytes(instance: number, precision?: number, binary?: boolean): string;
function ordinalize(instance: number): string;
function times<T>(instance: number, indexMapFn?: (i: number) => T): T[];
function clamp(instance: number, start?: number, end?: number): number;Object utilities for manipulation, analysis, and functional operations with deep merging and advanced querying.
// Key object methods
function merge<T>(instance: T, source: any, options?: ObjectMergeOptions): T;
function clone(instance: any, deep?: boolean): any;
function keys<T>(instance: T): string[];
function values<T>(instance: T): any[];
function filter<T>(instance: T, search: any): Partial<T>;
function fromQueryString<T>(str: string, options?: QueryStringParseOptions): T;
interface ObjectMergeOptions {
deep?: boolean;
hidden?: boolean;
descriptor?: boolean;
resolve?: boolean | Function;
}
interface QueryStringParseOptions<T = any, U = any> {
deep?: boolean;
auto?: boolean;
transform?: (key: string, val: any, obj: T) => U;
separator?: string;
}Regular expression utilities for escaping and flag manipulation.
// Key regexp methods
function escape(str?: string): string;
function getFlags(instance: RegExp): string;
function setFlags(instance: RegExp, flags: string): RegExp;
function addFlags(instance: RegExp, flags: string): RegExp;Comprehensive string operations including case conversion, encoding/decoding, truncation, and inflections.
// Key string methods
function camelize(instance: string, upper?: boolean): string;
function capitalize(instance: string, lower?: boolean, all?: boolean): string;
function truncate(instance: string, length: number, from?: string, ellipsis?: string): string;
function format(instance: string, ...args: any[]): string;
function escapeHTML(instance: string): string;
function pluralize(instance: string, num?: number): string;Range creation and iteration for dates, numbers, and strings with set operations and mathematical functions.
// Range class and methods
class Range {
constructor(start: any, end: any);
contains<T>(el: T): boolean;
every<T>(amount: string | number, everyFn?: (el: T, i: number, r: Range) => void): T[];
toArray<T>(): T[];
union(range: Range): Range;
intersect(range: Range): Range;
}Comprehensive internationalization support with 18 built-in locales and extensible locale system for dates and number formatting.
// Locale methods
function addLocale(localeCode: string, def: any): void;
function setLocale(localeCode: string): void;
function getLocale(localeCode?: string): Locale;
function getAllLocaleCodes(): string[];
interface Locale {
addFormat(src: string, to?: string[]): void;
getDuration(ms: number): string;
getFirstDayOfWeek(): number;
getMonthName(n: number): string;
getWeekdayName(n: number): string;
}interface ExtendOptions {
methods?: string[]; // Specific methods to include
except?: (string | Function)[]; // Methods/constructors to exclude
namespaces?: Function[]; // Namespaces to extend
enhance?: boolean; // Enable enhanced mode
enhanceString?: boolean; // String-specific enhancements
enhanceArray?: boolean; // Array-specific enhancements
objectPrototype?: boolean; // Allow Object.prototype extension
}
interface Sugar {
(opts?: ExtendOptions): Sugar;
extend(opts?: ExtendOptions): Sugar;
createNamespace(name: string): SugarNamespace;
Array: ArrayConstructor;
Date: DateConstructor;
Function: FunctionConstructor;
Number: NumberConstructor;
Object: ObjectConstructor;
RegExp: RegExpConstructor;
String: StringConstructor;
}All Sugar methods support chaining when used with the chainable interface:
interface SugarDefaultChainable<RawValue> {
raw: RawValue;
valueOf(): RawValue;
toString(): string;
// All module methods return chainable instances
}