Sugar.js Core Utilities

2.0.6 · maintenance · verified Sun Apr 19

Sugar-core is the foundational module for the Sugar.js JavaScript utility library, providing core functionalities and the mechanism to define new methods. Currently at stable version 2.0.6, the package itself was last published 7 years ago, suggesting a maintenance rather than active rapid development cadence for the core package specifically, although the broader Sugar.js project has more recent releases. It serves as a base for all other Sugar.js npm packages and allows plugin developers to extend the library with custom functionalities. A key differentiating factor is its approach to defining methods, specifically `defineInstance`, which expects the instance object as the first argument and explicitly discourages the use of `this` inside the method body (unless creating a polyfill). It also offers specific helpers like `defineInstanceAndStatic` for `Object` methods, as Sugar.js does not directly extend `Object.prototype` in extended mode. The library ships with TypeScript types, facilitating its use in modern TypeScript projects.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to define a custom instance method (`pluralize`) for the String prototype using `defineInstance` and its subsequent use.

import { defineInstance } from 'sugar-core';

// Demonstrates defining a custom instance method 'pluralize' for strings.
// This method, when defined, will be available on string instances if
// the main Sugar.js library is configured in 'extended mode'.
// The 'defineInstance' method expects the instance (the string itself)
// as its first argument and discourages using 'this'.
defineInstance('pluralize', function(str: string, count: number = 2): string {
  if (count === 1) {
    return str;
  }
  // Simple pluralization logic for demonstration purposes
  if (str.endsWith('y') && !str.endsWith('ay') && !str.endsWith('ey') && !str.endsWith('oy')) {
    return str.slice(0, -1) + 'ies';
  }
  return str + 's';
});

// Example usage (requires Sugar.js extended mode or chainables for full functionality)
const singleWord = 'cat';
const multipleWord = 'dog';
const trickyWord = 'fly';

console.log(`'${singleWord}' pluralized:`, (singleWord as any).pluralize(1)); // Expected: 'cat'
console.log(`'${singleWord}' pluralized:`, (singleWord as any).pluralize(2)); // Expected: 'cats'
console.log(`'${multipleWord}' pluralized:`, (multipleWord as any).pluralize()); // Expected: 'dogs'
console.log(`'${trickyWord}' pluralized:`, (trickyWord as any).pluralize()); // Expected: 'flies'

// Note: The 'as any' cast is used here to bypass TypeScript's type checking
// because 'sugar-core' extends native prototypes at runtime, which TS doesn't
// inherently know without explicit declaration merging.

view raw JSON →