or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-manipulation.mddatabase-management.mdindex.mdquerying-filtering.mdutility-functions.md

utility-functions.mddocs/

0

# Utility Functions

1

2

Static utility methods available on the TAFFY object for type checking, object manipulation, data comparison operations, and iteration helpers.

3

4

## Capabilities

5

6

### Type Checking Utilities

7

8

Comprehensive set of type checking functions that provide more accurate type detection than JavaScript's native typeof.

9

10

```javascript { .api }

11

/**

12

* Enhanced typeof that distinguishes arrays from objects

13

* @param value - Value to check type of

14

* @returns Type string: 'array', 'object', 'string', 'number', 'boolean', 'function', 'null', 'undefined'

15

*/

16

TAFFY.typeOf(value: any): string;

17

18

/**

19

* Check if value is a string

20

* @param value - Value to test

21

* @returns True if value is a string

22

*/

23

TAFFY.isString(value: any): boolean;

24

25

/**

26

* Check if value is a number

27

* @param value - Value to test

28

* @returns True if value is a number

29

*/

30

TAFFY.isNumber(value: any): boolean;

31

32

/**

33

* Check if value is an object (but not array or null)

34

* @param value - Value to test

35

* @returns True if value is an object

36

*/

37

TAFFY.isObject(value: any): boolean;

38

39

/**

40

* Check if value is an array

41

* @param value - Value to test

42

* @returns True if value is an array

43

*/

44

TAFFY.isArray(value: any): boolean;

45

46

/**

47

* Check if value is a boolean

48

* @param value - Value to test

49

* @returns True if value is a boolean

50

*/

51

TAFFY.isBoolean(value: any): boolean;

52

53

/**

54

* Check if value is null

55

* @param value - Value to test

56

* @returns True if value is null

57

*/

58

TAFFY.isNull(value: any): boolean;

59

60

/**

61

* Check if value is a function

62

* @param value - Value to test

63

* @returns True if value is a function

64

*/

65

TAFFY.isFunction(value: any): boolean;

66

67

/**

68

* Check if value is undefined

69

* @param value - Value to test

70

* @returns True if value is undefined

71

*/

72

TAFFY.isUndefined(value: any): boolean;

73

```

74

75

**Usage Examples:**

76

77

```javascript

78

const TAFFY = require('taffydb').taffy;

79

80

// Enhanced type detection

81

console.log(TAFFY.typeOf([])); // "array" (not "object" like typeof)

82

console.log(TAFFY.typeOf({})); // "object"

83

console.log(TAFFY.typeOf(null)); // "null" (not "object" like typeof)

84

console.log(TAFFY.typeOf("hello")); // "string"

85

86

// Specific type checking

87

const data = [

88

"hello", // string

89

42, // number

90

true, // boolean

91

null, // null

92

undefined, // undefined

93

[], // array

94

{}, // object

95

function() {} // function

96

];

97

98

data.forEach(item => {

99

console.log(`${item} is string: ${TAFFY.isString(item)}`);

100

console.log(`${item} is number: ${TAFFY.isNumber(item)}`);

101

console.log(`${item} is array: ${TAFFY.isArray(item)}`);

102

console.log(`${item} is object: ${TAFFY.isObject(item)}`);

103

});

104

105

// Conditional logic based on types

106

function processValue(value) {

107

if (TAFFY.isArray(value)) {

108

return value.map(item => processValue(item));

109

} else if (TAFFY.isObject(value)) {

110

const result = {};

111

for (let key in value) {

112

result[key] = processValue(value[key]);

113

}

114

return result;

115

} else if (TAFFY.isString(value)) {

116

return value.toLowerCase();

117

} else {

118

return value;

119

}

120

}

121

```

122

123

### Object Manipulation

124

125

Utilities for merging objects, getting object keys, and comparing object structures.

126

127

```javascript { .api }

128

/**

129

* Merge two objects, with obj2 properties overriding obj1

130

* @param obj1 - Base object

131

* @param obj2 - Object with overriding properties

132

* @returns New merged object

133

*/

134

TAFFY.mergeObj(obj1: object, obj2: object): object;

135

136

/**

137

* Get array of object property names, sorted alphabetically

138

* @param obj - Object to get keys from

139

* @returns Sorted array of property names

140

*/

141

TAFFY.getObjectKeys(obj: object): string[];

142

143

/**

144

* Deep comparison of two objects for equality

145

* @param obj1 - First object to compare

146

* @param obj2 - Second object to compare

147

* @returns True if objects are structurally identical

148

*/

149

TAFFY.isSameObject(obj1: object, obj2: object): boolean;

150

151

/**

152

* Compare two arrays for equality

153

* @param arr1 - First array to compare

154

* @param arr2 - Second array to compare

155

* @returns True if arrays contain same elements in same order

156

*/

157

TAFFY.isSameArray(arr1: any[], arr2: any[]): boolean;

158

```

159

160

**Usage Examples:**

161

162

```javascript

163

// Object merging

164

const defaults = {

165

theme: 'light',

166

language: 'en',

167

notifications: true

168

};

169

const userPrefs = {

170

theme: 'dark',

171

notifications: false

172

};

173

const settings = TAFFY.mergeObj(defaults, userPrefs);

174

// Result: { theme: 'dark', language: 'en', notifications: false }

175

176

// Get object keys

177

const user = { name: 'Alice', age: 30, email: 'alice@example.com', active: true };

178

const keys = TAFFY.getObjectKeys(user);

179

// Result: ['active', 'age', 'email', 'name'] (sorted)

180

181

// Object comparison

182

const obj1 = { name: 'John', age: 25, skills: ['JS', 'React'] };

183

const obj2 = { name: 'John', age: 25, skills: ['JS', 'React'] };

184

const obj3 = { name: 'John', age: 26, skills: ['JS', 'React'] };

185

186

console.log(TAFFY.isSameObject(obj1, obj2)); // true

187

console.log(TAFFY.isSameObject(obj1, obj3)); // false

188

189

// Array comparison

190

const arr1 = ['apple', 'banana', 'cherry'];

191

const arr2 = ['apple', 'banana', 'cherry'];

192

const arr3 = ['apple', 'cherry', 'banana'];

193

194

console.log(TAFFY.isSameArray(arr1, arr2)); // true

195

console.log(TAFFY.isSameArray(arr1, arr3)); // false

196

197

// Practical usage in validation

198

function validateConfig(newConfig, defaultConfig) {

199

const requiredKeys = TAFFY.getObjectKeys(defaultConfig);

200

const providedKeys = TAFFY.getObjectKeys(newConfig);

201

202

const missingKeys = requiredKeys.filter(key => !providedKeys.includes(key));

203

if (missingKeys.length > 0) {

204

throw new Error(`Missing required config keys: ${missingKeys.join(', ')}`);

205

}

206

207

return TAFFY.mergeObj(defaultConfig, newConfig);

208

}

209

```

210

211

### Data Search and Comparison

212

213

Utilities for searching within complex data structures and checking containment.

214

215

```javascript { .api }

216

/**

217

* Check if container contains the specified value

218

* Supports objects, arrays, strings, and TaffyDB instances

219

* @param container - Container to search in

220

* @param value - Value to search for

221

* @returns True if container contains the value

222

*/

223

TAFFY.has(container: any, value: any): boolean;

224

225

/**

226

* Check if container contains all specified values

227

* @param container - Container to search in

228

* @param values - Values to search for (can be array or single value)

229

* @returns True if container contains all values

230

*/

231

TAFFY.hasAll(container: any, values: any | any[]): boolean;

232

```

233

234

**Usage Examples:**

235

236

```javascript

237

// String containment

238

console.log(TAFFY.has("hello world", "world")); // true

239

console.log(TAFFY.has("hello world", "xyz")); // false

240

241

// Array containment

242

const numbers = [1, 2, 3, 4, 5];

243

console.log(TAFFY.has(numbers, 3)); // true

244

console.log(TAFFY.has(numbers, 10)); // false

245

246

// Object property containment

247

const user = { name: 'Alice', age: 30, email: 'alice@example.com' };

248

console.log(TAFFY.has(user, 'email')); // true (has property 'email')

249

console.log(TAFFY.has(user, 'phone')); // false

250

251

// Nested object search

252

const data = { user: { profile: { name: 'Bob' } } };

253

console.log(TAFFY.has(data, { user: { profile: { name: 'Bob' } } })); // true

254

255

// Array of objects search

256

const users = [

257

{ name: 'Alice', role: 'admin' },

258

{ name: 'Bob', role: 'user' }

259

];

260

console.log(TAFFY.has(users, { name: 'Alice' })); // true

261

262

// hasAll for multiple values

263

const skills = ['JavaScript', 'React', 'Node.js', 'Python'];

264

console.log(TAFFY.hasAll(skills, ['JavaScript', 'React'])); // true

265

console.log(TAFFY.hasAll(skills, ['JavaScript', 'PHP'])); // false

266

console.log(TAFFY.hasAll(skills, 'JavaScript')); // true (single value)

267

268

// Complex containment checking

269

function hasRequiredPermissions(user, requiredPerms) {

270

return TAFFY.hasAll(user.permissions, requiredPerms);

271

}

272

273

const adminUser = {

274

name: 'Admin',

275

permissions: ['read', 'write', 'delete', 'admin']

276

};

277

console.log(hasRequiredPermissions(adminUser, ['read', 'write'])); // true

278

console.log(hasRequiredPermissions(adminUser, ['read', 'super'])); // false

279

```

280

281

### Iteration Helpers

282

283

Utilities for iterating over arrays and objects with control flow support.

284

285

```javascript { .api }

286

/**

287

* Iterate over arrays with enhanced control flow

288

* @param collection - Array to iterate over

289

* @param callback - Function called for each item (item, index, array)

290

*/

291

TAFFY.each(collection: any[], callback: (item: any, index: number, array: any[]) => any): void;

292

293

/**

294

* Iterate over object properties

295

* @param obj - Object to iterate over

296

* @param callback - Function called for each property (value, key, object)

297

*/

298

TAFFY.eachin(obj: object, callback: (value: any, key: string, object: object) => any): void;

299

```

300

301

**Usage Examples:**

302

303

```javascript

304

// Array iteration with each

305

const numbers = [1, 2, 3, 4, 5];

306

TAFFY.each(numbers, function(item, index, array) {

307

console.log(`Item ${index}: ${item}`);

308

309

// Return TAFFY.EXIT to break early

310

if (item === 3) return TAFFY.EXIT;

311

});

312

313

// Object property iteration with eachin

314

const config = {

315

host: 'localhost',

316

port: 3000,

317

ssl: false,

318

timeout: 5000

319

};

320

321

TAFFY.eachin(config, function(value, key, obj) {

322

console.log(`${key}: ${value} (${typeof value})`);

323

});

324

325

// Practical examples

326

function validateArrayData(data, validators) {

327

const errors = [];

328

329

TAFFY.each(data, function(item, index) {

330

TAFFY.eachin(validators, function(validator, field) {

331

if (!validator(item[field])) {

332

errors.push(`Item ${index}, field '${field}': validation failed`);

333

}

334

});

335

});

336

337

return errors;

338

}

339

340

// Summing object values

341

function sumObjectValues(obj) {

342

let total = 0;

343

TAFFY.eachin(obj, function(value, key) {

344

if (TAFFY.isNumber(value)) {

345

total += value;

346

}

347

});

348

return total;

349

}

350

351

const sales = { jan: 1000, feb: 1200, mar: 950, apr: 1100 };

352

console.log(`Total sales: $${sumObjectValues(sales)}`); // Total sales: $4250

353

```

354

355

### Extension Support

356

357

Utilities for extending TaffyDB functionality with custom methods.

358

359

```javascript { .api }

360

/**

361

* Add custom methods to the TaffyDB query API

362

* @param methodName - Name of the new method

363

* @param fn - Function implementation

364

*/

365

TAFFY.extend(methodName: string, fn: function): void;

366

367

/**

368

* Special return value to exit early from iteration functions

369

*/

370

TAFFY.EXIT: 'TAFFYEXIT';

371

```

372

373

**Usage Examples:**

374

375

```javascript

376

// Add custom query method

377

TAFFY.extend('findByEmail', function(email) {

378

return this.filter({ email: { is: email } });

379

});

380

381

// Use custom method

382

const userDB = TAFFY([

383

{ id: 1, name: 'Alice', email: 'alice@example.com' },

384

{ id: 2, name: 'Bob', email: 'bob@example.com' }

385

]);

386

387

const alice = userDB().findByEmail('alice@example.com').first();

388

389

// Add pagination method

390

TAFFY.extend('paginate', function(page, pageSize) {

391

const start = (page - 1) * pageSize + 1;

392

return this.start(start).limit(pageSize);

393

});

394

395

// Use pagination

396

const page2Users = userDB().paginate(2, 10).get();

397

398

// Add statistics method

399

TAFFY.extend('stats', function(column) {

400

const values = this.select(column);

401

const sum = values.reduce((a, b) => a + b, 0);

402

return {

403

count: values.length,

404

sum: sum,

405

avg: sum / values.length,

406

min: Math.min(...values),

407

max: Math.max(...values)

408

};

409

});

410

411

// Use statistics

412

const salaryStats = userDB({ department: 'Engineering' }).stats('salary');

413

console.log(`Avg salary: $${salaryStats.avg.toFixed(2)}`);

414

415

// Using TAFFY.EXIT for early termination

416

function findFirstMatch(array, predicate) {

417

let result = null;

418

TAFFY.each(array, function(item, index) {

419

if (predicate(item)) {

420

result = item;

421

return TAFFY.EXIT; // Stop iteration

422

}

423

});

424

return result;

425

}

426

```