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

function.mddocs/

0

# Function Module

1

2

Enhanced function utilities providing control, timing, and enhancement capabilities for JavaScript functions.

3

4

## Core Imports

5

6

```javascript

7

// Import Sugar namespace

8

import Sugar from "sugar";

9

// Methods available as Sugar.Function.methodName()

10

```

11

12

CommonJS:

13

```javascript

14

const Sugar = require("sugar");

15

// Methods available as Sugar.Function.methodName()

16

Sugar.Function.after(fn, 3);

17

```

18

19

## Capabilities

20

21

### Function Control

22

23

Control when and how many times functions execute.

24

25

#### After

26

27

Creates a function that executes only after being called `n` times.

28

29

```javascript { .api }

30

/**

31

* Creates a function that executes only after being called n times

32

* @param instance - Function to control

33

* @param n - Number of calls required before execution

34

* @returns Function that executes after n calls

35

*/

36

function after(instance: Function, n: number): Function;

37

```

38

39

**Usage Example:**

40

```javascript

41

import Sugar from "sugar";

42

43

const fn = Sugar.Function.after(() => console.log('Called!'), 3);

44

fn(); // Nothing happens

45

fn(); // Nothing happens

46

fn(); // Logs 'Called!'

47

fn(); // Logs 'Called!' (continues to work)

48

```

49

50

#### Once

51

52

Creates a function that executes only on the first call, ignoring subsequent calls.

53

54

```javascript { .api }

55

/**

56

* Creates a function that executes only once

57

* @param instance - Function to execute once

58

* @returns Function that executes only on first call

59

*/

60

function once(instance: Function): Function;

61

```

62

63

**Usage Example:**

64

```javascript

65

import Sugar from "sugar";

66

67

let counter = 0;

68

const increment = Sugar.Function.once(() => counter++);

69

increment(); // counter becomes 1

70

increment(); // counter stays 1

71

increment(); // counter stays 1

72

```

73

74

#### Lock

75

76

Locks a function after `n` executions, preventing further calls.

77

78

```javascript { .api }

79

/**

80

* Locks function after n executions

81

* @param instance - Function to lock

82

* @param n - Number of executions before locking (default: 1)

83

* @returns Function that locks after n calls

84

*/

85

function lock(instance: Function, n?: number): Function;

86

```

87

88

**Usage Example:**

89

```javascript

90

import Sugar from "sugar";

91

92

let calls = 0;

93

const fn = Sugar.Function.lock(() => calls++, 2);

94

fn(); // calls becomes 1

95

fn(); // calls becomes 2

96

fn(); // calls stays 2 (locked)

97

```

98

99

#### Cancel

100

101

Cancels a delayed or recurring function, preventing future executions.

102

103

```javascript { .api }

104

/**

105

* Cancels delayed or recurring function execution

106

* @param instance - Function to cancel

107

* @returns The function instance

108

*/

109

function cancel(instance: Function): Function;

110

```

111

112

**Usage Example:**

113

```javascript

114

import Sugar from "sugar";

115

116

const fn = Sugar.Function.delay(() => console.log('Delayed'), 1000);

117

Sugar.Function.cancel(fn); // Prevents the delayed execution

118

```

119

120

### Function Timing

121

122

Control the timing and frequency of function execution.

123

124

#### Delay

125

126

Delays function execution by specified milliseconds.

127

128

```javascript { .api }

129

/**

130

* Delays function execution

131

* @param instance - Function to delay

132

* @param ms - Milliseconds to delay (default: 1)

133

* @param args - Arguments to pass to function

134

* @returns The delayed function

135

*/

136

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

137

```

138

139

**Usage Example:**

140

```javascript

141

import Sugar from "sugar";

142

143

Sugar.Function.delay(() => console.log('Hello after 1 second'), 1000);

144

145

// With arguments

146

Sugar.Function.delay((name, age) => console.log(`${name} is ${age}`), 500, 'Alice', 25);

147

```

148

149

#### Debounce

150

151

Creates a debounced function that delays execution until after calls have stopped.

152

153

```javascript { .api }

154

/**

155

* Creates debounced function that delays execution

156

* @param instance - Function to debounce

157

* @param ms - Milliseconds to wait (default: 1)

158

* @returns Debounced function

159

*/

160

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

161

```

162

163

**Usage Example:**

164

```javascript

165

import Sugar from "sugar";

166

167

const search = Sugar.Function.debounce((query) => {

168

console.log('Searching for:', query);

169

}, 300);

170

171

// Only the last call within 300ms will execute

172

search('a');

173

search('ab');

174

search('abc'); // Only this will execute after 300ms

175

```

176

177

#### Throttle

178

179

Creates a throttled function that executes at most once per specified interval.

180

181

```javascript { .api }

182

/**

183

* Creates throttled function with limited execution frequency

184

* @param instance - Function to throttle

185

* @param ms - Milliseconds between executions (default: 1)

186

* @returns Throttled function

187

*/

188

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

189

```

190

191

**Usage Example:**

192

```javascript

193

import Sugar from "sugar";

194

195

const handleScroll = Sugar.Function.throttle(() => {

196

console.log('Scroll event handled');

197

}, 100);

198

199

window.addEventListener('scroll', handleScroll);

200

// Function executes at most once every 100ms during scrolling

201

```

202

203

#### Every

204

205

Executes a function repeatedly at specified intervals.

206

207

```javascript { .api }

208

/**

209

* Executes function repeatedly at intervals

210

* @param instance - Function to execute repeatedly

211

* @param ms - Milliseconds between executions (default: 1)

212

* @param args - Arguments to pass to function

213

* @returns The recurring function (can be cancelled)

214

*/

215

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

216

```

217

218

**Usage Example:**

219

```javascript

220

import Sugar from "sugar";

221

222

const timer = Sugar.Function.every(() => console.log('Tick'), 1000);

223

// Logs 'Tick' every second

224

225

// Cancel after 5 seconds

226

setTimeout(() => Sugar.Function.cancel(timer), 5000);

227

```

228

229

#### Lazy

230

231

Creates a lazy function with rate limiting and optional immediate execution.

232

233

```javascript { .api }

234

/**

235

* Creates lazy function with rate limiting

236

* @param instance - Function to make lazy

237

* @param ms - Milliseconds for rate limiting (default: 1)

238

* @param immediate - Execute immediately on first call (default: false)

239

* @param limit - Maximum number of executions (optional)

240

* @returns Lazy function with rate limiting

241

*/

242

function lazy(instance: Function, ms?: number, immediate?: boolean, limit?: number): Function;

243

```

244

245

**Usage Example:**

246

```javascript

247

import Sugar from "sugar";

248

249

// Execute immediately, then limit to once per 2 seconds, max 3 times

250

const lazyFn = Sugar.Function.lazy(() => console.log('Lazy execution'), 2000, true, 3);

251

252

lazyFn(); // Executes immediately

253

lazyFn(); // Waits 2 seconds

254

lazyFn(); // Waits 2 seconds

255

lazyFn(); // Does nothing (limit reached)

256

```

257

258

### Function Enhancement

259

260

Enhance function capabilities with memoization and partial application.

261

262

#### Memoize

263

264

Creates a memoized function that caches results based on arguments.

265

266

```javascript { .api }

267

/**

268

* Creates memoized function with result caching

269

* @param instance - Function to memoize

270

* @param hashFn - Custom hash function for cache keys (optional)

271

* @param limit - Maximum cache size (optional)

272

* @returns Memoized function with caching

273

*/

274

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

275

```

276

277

**Usage Example:**

278

```javascript

279

import Sugar from "sugar";

280

281

const expensiveOperation = Sugar.Function.memoize((n) => {

282

console.log('Computing...', n);

283

return n * n * n;

284

});

285

286

console.log(expensiveOperation(5)); // Logs 'Computing... 5', returns 125

287

console.log(expensiveOperation(5)); // Returns 125 immediately (cached)

288

289

// Custom hash function for objects

290

const objectMemo = Sugar.Function.memoize(

291

(obj) => obj.value * 2,

292

(obj) => JSON.stringify(obj)

293

);

294

295

// Limit cache size to 10 entries

296

const limitedMemo = Sugar.Function.memoize((x) => x * x, null, 10);

297

```

298

299

#### Partial

300

301

Creates a partially applied function with pre-filled arguments.

302

303

```javascript { .api }

304

/**

305

* Creates partially applied function

306

* @param instance - Function to partially apply

307

* @param args - Arguments to pre-fill

308

* @returns Partially applied function

309

*/

310

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

311

```

312

313

**Usage Example:**

314

```javascript

315

import Sugar from "sugar";

316

317

const multiply = (a, b, c) => a * b * c;

318

const double = Sugar.Function.partial(multiply, 2);

319

const quadruple = Sugar.Function.partial(multiply, 2, 2);

320

321

console.log(double(3, 4)); // 2 * 3 * 4 = 24

322

console.log(quadruple(5)); // 2 * 2 * 5 = 20

323

324

// Useful for event handlers

325

const logWithPrefix = (prefix, message) => console.log(`${prefix}: ${message}`);

326

const errorLog = Sugar.Function.partial(logWithPrefix, 'ERROR');

327

const infoLog = Sugar.Function.partial(logWithPrefix, 'INFO');

328

329

errorLog('Something went wrong'); // Logs: ERROR: Something went wrong

330

infoLog('Operation completed'); // Logs: INFO: Operation completed

331

```