or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array.mddate.mdfunction.mdindex.mdlocalization.mdnumber.mdobject.mdrange.mdregexp.mdstring.md

index.mddocs/

0

# Sugar

1

2

Sugar 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.

3

4

## Package Information

5

6

- **Package Name**: sugar

7

- **Package Type**: npm

8

- **Language**: JavaScript with TypeScript definitions

9

- **Installation**: `npm install sugar`

10

11

## Core Imports

12

13

Sugar can be used in multiple ways depending on your needs:

14

15

**Complete Sugar with global extension:**

16

```javascript

17

import Sugar from "sugar";

18

// Extends all native prototypes automatically

19

```

20

21

**Modular approach with namespace:**

22

```javascript

23

import Sugar from "sugar";

24

// Use Sugar.Array.map(), Sugar.String.format(), etc.

25

```

26

27

**Specific module imports:**

28

```javascript

29

import Sugar from "sugar";

30

const { Array: SugarArray, Date: SugarDate } = Sugar;

31

```

32

33

**CommonJS:**

34

```javascript

35

const Sugar = require("sugar");

36

```

37

38

**With custom configuration:**

39

```javascript

40

import Sugar from "sugar";

41

Sugar.extend({

42

namespaces: [Array, Object, String], // Only extend these

43

methods: ['map', 'filter', 'format'], // Only these methods

44

enhance: false // Disable enhanced mode

45

});

46

```

47

48

## Basic Usage

49

50

```javascript

51

import Sugar from "sugar";

52

53

// Array operations

54

const users = [

55

{ name: 'Alice', age: 25, active: true },

56

{ name: 'Bob', age: 30, active: false },

57

{ name: 'Charlie', age: 35, active: true }

58

];

59

60

// Find active users over 25

61

const activeUsers = Sugar.Array.filter(users, { active: true })

62

.filter(user => user.age > 25);

63

64

// Date parsing and formatting

65

const date = Sugar.Date.create('next Friday at 3pm');

66

const formatted = Sugar.Date.format(date, '{Weekday} {Month} {dd}, {yyyy}');

67

68

// String manipulation

69

const slug = Sugar.String.parameterize('Hello World Example');

70

// Result: "hello-world-example"

71

72

// Number formatting

73

const price = Sugar.Number.format(1234.56, 2);

74

// Result: "1,234.56"

75

76

// Object operations

77

const config = Sugar.Object.merge(

78

{ timeout: 5000, retries: 3 },

79

{ timeout: 10000, debug: true }

80

);

81

// Result: { timeout: 10000, retries: 3, debug: true }

82

```

83

84

## Architecture

85

86

Sugar is built around several key architectural patterns:

87

88

- **Native Extension**: Methods can be added to native prototypes or used through namespaces

89

- **Modular Design**: Each module (Array, Date, etc.) is independent and can be used separately

90

- **Chainable API**: Many operations support method chaining for fluent interfaces

91

- **Type Safety**: Comprehensive TypeScript definitions with generic type preservation

92

- **Internationalization**: Built-in support for 18+ locales with date parsing and formatting

93

- **Configuration**: Flexible extension options for customizing which methods are available

94

95

## Capabilities

96

97

### Array Operations

98

99

Comprehensive array manipulation including functional programming utilities, statistical operations, and advanced filtering.

100

101

```javascript { .api }

102

// Key array methods

103

function map<T,U>(instance: T[], mapFn: (el: T, i: number, arr: T[]) => U): U[];

104

function filter<T>(instance: T[], search: any): T[];

105

function find<T>(instance: T[], search: any): T | undefined;

106

function unique<T>(instance: T[], mapFn?: (el: T) => any): T[];

107

function groupBy<T,U>(instance: T[], mapFn: (el: T) => U): { [key: string]: T[] };

108

function sortBy<T,U>(instance: T[], mapFn?: (el: T) => U, desc?: boolean): T[];

109

```

110

111

[Array Operations](./array.md)

112

113

### Date Parsing & Formatting

114

115

Advanced date parsing with natural language support, extensive formatting options, and comprehensive internationalization covering 18+ locales.

116

117

```javascript { .api }

118

// Key date methods

119

function create(d?: any, options?: DateCreateOptions): Date;

120

function format(instance: Date, format?: string, locale?: string): string;

121

function relative(instance: Date, locale?: string): string;

122

function advance(instance: Date, set: any, reset?: boolean): Date;

123

function isValid(instance: Date): boolean;

124

function range(start?: any, end?: any): Range;

125

126

interface DateCreateOptions {

127

locale?: string;

128

past?: boolean;

129

future?: boolean;

130

fromUTC?: boolean;

131

setUTC?: boolean;

132

}

133

```

134

135

[Date Operations](./date.md)

136

137

### Function Enhancement

138

139

Function utilities for timing control, memoization, and functional programming patterns.

140

141

```javascript { .api }

142

// Key function methods

143

function debounce(instance: Function, ms?: number): Function;

144

function throttle(instance: Function, ms?: number): Function;

145

function delay(instance: Function, ms?: number, ...args: any[]): number;

146

function memoize(instance: Function, hashFn?: Function): Function;

147

function once(instance: Function): Function;

148

function partial(instance: Function, ...args: any[]): Function;

149

```

150

151

[Function Utilities](./function.md)

152

153

### Number Formatting & Math

154

155

Number formatting, mathematical operations, and iteration utilities with locale-aware formatting.

156

157

```javascript { .api }

158

// Key number methods

159

function format(instance: number, precision?: number): string;

160

function abbr(instance: number, precision?: number): string;

161

function bytes(instance: number, precision?: number, binary?: boolean): string;

162

function ordinalize(instance: number): string;

163

function times<T>(instance: number, indexMapFn?: (i: number) => T): T[];

164

function clamp(instance: number, start?: number, end?: number): number;

165

```

166

167

[Number Operations](./number.md)

168

169

### Object Manipulation

170

171

Object utilities for manipulation, analysis, and functional operations with deep merging and advanced querying.

172

173

```javascript { .api }

174

// Key object methods

175

function merge<T>(instance: T, source: any, options?: ObjectMergeOptions): T;

176

function clone(instance: any, deep?: boolean): any;

177

function keys<T>(instance: T): string[];

178

function values<T>(instance: T): any[];

179

function filter<T>(instance: T, search: any): Partial<T>;

180

function fromQueryString<T>(str: string, options?: QueryStringParseOptions): T;

181

182

interface ObjectMergeOptions {

183

deep?: boolean;

184

hidden?: boolean;

185

descriptor?: boolean;

186

resolve?: boolean | Function;

187

}

188

189

interface QueryStringParseOptions<T = any, U = any> {

190

deep?: boolean;

191

auto?: boolean;

192

transform?: (key: string, val: any, obj: T) => U;

193

separator?: string;

194

}

195

```

196

197

[Object Operations](./object.md)

198

199

### Regular Expressions

200

201

Regular expression utilities for escaping and flag manipulation.

202

203

```javascript { .api }

204

// Key regexp methods

205

function escape(str?: string): string;

206

function getFlags(instance: RegExp): string;

207

function setFlags(instance: RegExp, flags: string): RegExp;

208

function addFlags(instance: RegExp, flags: string): RegExp;

209

```

210

211

[RegExp Utilities](./regexp.md)

212

213

### String Manipulation

214

215

Comprehensive string operations including case conversion, encoding/decoding, truncation, and inflections.

216

217

```javascript { .api }

218

// Key string methods

219

function camelize(instance: string, upper?: boolean): string;

220

function capitalize(instance: string, lower?: boolean, all?: boolean): string;

221

function truncate(instance: string, length: number, from?: string, ellipsis?: string): string;

222

function format(instance: string, ...args: any[]): string;

223

function escapeHTML(instance: string): string;

224

function pluralize(instance: string, num?: number): string;

225

```

226

227

[String Operations](./string.md)

228

229

### Range Operations

230

231

Range creation and iteration for dates, numbers, and strings with set operations and mathematical functions.

232

233

```javascript { .api }

234

// Range class and methods

235

class Range {

236

constructor(start: any, end: any);

237

contains<T>(el: T): boolean;

238

every<T>(amount: string | number, everyFn?: (el: T, i: number, r: Range) => void): T[];

239

toArray<T>(): T[];

240

union(range: Range): Range;

241

intersect(range: Range): Range;

242

}

243

```

244

245

[Range Operations](./range.md)

246

247

### Localization & Internationalization

248

249

Comprehensive internationalization support with 18 built-in locales and extensible locale system for dates and number formatting.

250

251

```javascript { .api }

252

// Locale methods

253

function addLocale(localeCode: string, def: any): void;

254

function setLocale(localeCode: string): void;

255

function getLocale(localeCode?: string): Locale;

256

function getAllLocaleCodes(): string[];

257

258

interface Locale {

259

addFormat(src: string, to?: string[]): void;

260

getDuration(ms: number): string;

261

getFirstDayOfWeek(): number;

262

getMonthName(n: number): string;

263

getWeekdayName(n: number): string;

264

}

265

```

266

267

[Localization](./localization.md)

268

269

## Extension Configuration

270

271

```javascript { .api }

272

interface ExtendOptions {

273

methods?: string[]; // Specific methods to include

274

except?: (string | Function)[]; // Methods/constructors to exclude

275

namespaces?: Function[]; // Namespaces to extend

276

enhance?: boolean; // Enable enhanced mode

277

enhanceString?: boolean; // String-specific enhancements

278

enhanceArray?: boolean; // Array-specific enhancements

279

objectPrototype?: boolean; // Allow Object.prototype extension

280

}

281

282

interface Sugar {

283

(opts?: ExtendOptions): Sugar;

284

extend(opts?: ExtendOptions): Sugar;

285

createNamespace(name: string): SugarNamespace;

286

Array: ArrayConstructor;

287

Date: DateConstructor;

288

Function: FunctionConstructor;

289

Number: NumberConstructor;

290

Object: ObjectConstructor;

291

RegExp: RegExpConstructor;

292

String: StringConstructor;

293

}

294

```

295

296

## Chainable API

297

298

All Sugar methods support chaining when used with the chainable interface:

299

300

```javascript { .api }

301

interface SugarDefaultChainable<RawValue> {

302

raw: RawValue;

303

valueOf(): RawValue;

304

toString(): string;

305

// All module methods return chainable instances

306

}

307

```