JavaScript in-memory database with SQL-like query capabilities for array manipulation
—
Static utility methods available on the TAFFY object for type checking, object manipulation, data comparison operations, and iteration helpers.
Comprehensive set of type checking functions that provide more accurate type detection than JavaScript's native typeof.
/**
* Enhanced typeof that distinguishes arrays from objects
* @param value - Value to check type of
* @returns Type string: 'array', 'object', 'string', 'number', 'boolean', 'function', 'null', 'undefined'
*/
TAFFY.typeOf(value: any): string;
/**
* Check if value is a string
* @param value - Value to test
* @returns True if value is a string
*/
TAFFY.isString(value: any): boolean;
/**
* Check if value is a number
* @param value - Value to test
* @returns True if value is a number
*/
TAFFY.isNumber(value: any): boolean;
/**
* Check if value is an object (but not array or null)
* @param value - Value to test
* @returns True if value is an object
*/
TAFFY.isObject(value: any): boolean;
/**
* Check if value is an array
* @param value - Value to test
* @returns True if value is an array
*/
TAFFY.isArray(value: any): boolean;
/**
* Check if value is a boolean
* @param value - Value to test
* @returns True if value is a boolean
*/
TAFFY.isBoolean(value: any): boolean;
/**
* Check if value is null
* @param value - Value to test
* @returns True if value is null
*/
TAFFY.isNull(value: any): boolean;
/**
* Check if value is a function
* @param value - Value to test
* @returns True if value is a function
*/
TAFFY.isFunction(value: any): boolean;
/**
* Check if value is undefined
* @param value - Value to test
* @returns True if value is undefined
*/
TAFFY.isUndefined(value: any): boolean;Usage Examples:
const TAFFY = require('taffydb').taffy;
// Enhanced type detection
console.log(TAFFY.typeOf([])); // "array" (not "object" like typeof)
console.log(TAFFY.typeOf({})); // "object"
console.log(TAFFY.typeOf(null)); // "null" (not "object" like typeof)
console.log(TAFFY.typeOf("hello")); // "string"
// Specific type checking
const data = [
"hello", // string
42, // number
true, // boolean
null, // null
undefined, // undefined
[], // array
{}, // object
function() {} // function
];
data.forEach(item => {
console.log(`${item} is string: ${TAFFY.isString(item)}`);
console.log(`${item} is number: ${TAFFY.isNumber(item)}`);
console.log(`${item} is array: ${TAFFY.isArray(item)}`);
console.log(`${item} is object: ${TAFFY.isObject(item)}`);
});
// Conditional logic based on types
function processValue(value) {
if (TAFFY.isArray(value)) {
return value.map(item => processValue(item));
} else if (TAFFY.isObject(value)) {
const result = {};
for (let key in value) {
result[key] = processValue(value[key]);
}
return result;
} else if (TAFFY.isString(value)) {
return value.toLowerCase();
} else {
return value;
}
}Utilities for merging objects, getting object keys, and comparing object structures.
/**
* Merge two objects, with obj2 properties overriding obj1
* @param obj1 - Base object
* @param obj2 - Object with overriding properties
* @returns New merged object
*/
TAFFY.mergeObj(obj1: object, obj2: object): object;
/**
* Get array of object property names, sorted alphabetically
* @param obj - Object to get keys from
* @returns Sorted array of property names
*/
TAFFY.getObjectKeys(obj: object): string[];
/**
* Deep comparison of two objects for equality
* @param obj1 - First object to compare
* @param obj2 - Second object to compare
* @returns True if objects are structurally identical
*/
TAFFY.isSameObject(obj1: object, obj2: object): boolean;
/**
* Compare two arrays for equality
* @param arr1 - First array to compare
* @param arr2 - Second array to compare
* @returns True if arrays contain same elements in same order
*/
TAFFY.isSameArray(arr1: any[], arr2: any[]): boolean;Usage Examples:
// Object merging
const defaults = {
theme: 'light',
language: 'en',
notifications: true
};
const userPrefs = {
theme: 'dark',
notifications: false
};
const settings = TAFFY.mergeObj(defaults, userPrefs);
// Result: { theme: 'dark', language: 'en', notifications: false }
// Get object keys
const user = { name: 'Alice', age: 30, email: 'alice@example.com', active: true };
const keys = TAFFY.getObjectKeys(user);
// Result: ['active', 'age', 'email', 'name'] (sorted)
// Object comparison
const obj1 = { name: 'John', age: 25, skills: ['JS', 'React'] };
const obj2 = { name: 'John', age: 25, skills: ['JS', 'React'] };
const obj3 = { name: 'John', age: 26, skills: ['JS', 'React'] };
console.log(TAFFY.isSameObject(obj1, obj2)); // true
console.log(TAFFY.isSameObject(obj1, obj3)); // false
// Array comparison
const arr1 = ['apple', 'banana', 'cherry'];
const arr2 = ['apple', 'banana', 'cherry'];
const arr3 = ['apple', 'cherry', 'banana'];
console.log(TAFFY.isSameArray(arr1, arr2)); // true
console.log(TAFFY.isSameArray(arr1, arr3)); // false
// Practical usage in validation
function validateConfig(newConfig, defaultConfig) {
const requiredKeys = TAFFY.getObjectKeys(defaultConfig);
const providedKeys = TAFFY.getObjectKeys(newConfig);
const missingKeys = requiredKeys.filter(key => !providedKeys.includes(key));
if (missingKeys.length > 0) {
throw new Error(`Missing required config keys: ${missingKeys.join(', ')}`);
}
return TAFFY.mergeObj(defaultConfig, newConfig);
}Utilities for searching within complex data structures and checking containment.
/**
* Check if container contains the specified value
* Supports objects, arrays, strings, and TaffyDB instances
* @param container - Container to search in
* @param value - Value to search for
* @returns True if container contains the value
*/
TAFFY.has(container: any, value: any): boolean;
/**
* Check if container contains all specified values
* @param container - Container to search in
* @param values - Values to search for (can be array or single value)
* @returns True if container contains all values
*/
TAFFY.hasAll(container: any, values: any | any[]): boolean;Usage Examples:
// String containment
console.log(TAFFY.has("hello world", "world")); // true
console.log(TAFFY.has("hello world", "xyz")); // false
// Array containment
const numbers = [1, 2, 3, 4, 5];
console.log(TAFFY.has(numbers, 3)); // true
console.log(TAFFY.has(numbers, 10)); // false
// Object property containment
const user = { name: 'Alice', age: 30, email: 'alice@example.com' };
console.log(TAFFY.has(user, 'email')); // true (has property 'email')
console.log(TAFFY.has(user, 'phone')); // false
// Nested object search
const data = { user: { profile: { name: 'Bob' } } };
console.log(TAFFY.has(data, { user: { profile: { name: 'Bob' } } })); // true
// Array of objects search
const users = [
{ name: 'Alice', role: 'admin' },
{ name: 'Bob', role: 'user' }
];
console.log(TAFFY.has(users, { name: 'Alice' })); // true
// hasAll for multiple values
const skills = ['JavaScript', 'React', 'Node.js', 'Python'];
console.log(TAFFY.hasAll(skills, ['JavaScript', 'React'])); // true
console.log(TAFFY.hasAll(skills, ['JavaScript', 'PHP'])); // false
console.log(TAFFY.hasAll(skills, 'JavaScript')); // true (single value)
// Complex containment checking
function hasRequiredPermissions(user, requiredPerms) {
return TAFFY.hasAll(user.permissions, requiredPerms);
}
const adminUser = {
name: 'Admin',
permissions: ['read', 'write', 'delete', 'admin']
};
console.log(hasRequiredPermissions(adminUser, ['read', 'write'])); // true
console.log(hasRequiredPermissions(adminUser, ['read', 'super'])); // falseUtilities for iterating over arrays and objects with control flow support.
/**
* Iterate over arrays with enhanced control flow
* @param collection - Array to iterate over
* @param callback - Function called for each item (item, index, array)
*/
TAFFY.each(collection: any[], callback: (item: any, index: number, array: any[]) => any): void;
/**
* Iterate over object properties
* @param obj - Object to iterate over
* @param callback - Function called for each property (value, key, object)
*/
TAFFY.eachin(obj: object, callback: (value: any, key: string, object: object) => any): void;Usage Examples:
// Array iteration with each
const numbers = [1, 2, 3, 4, 5];
TAFFY.each(numbers, function(item, index, array) {
console.log(`Item ${index}: ${item}`);
// Return TAFFY.EXIT to break early
if (item === 3) return TAFFY.EXIT;
});
// Object property iteration with eachin
const config = {
host: 'localhost',
port: 3000,
ssl: false,
timeout: 5000
};
TAFFY.eachin(config, function(value, key, obj) {
console.log(`${key}: ${value} (${typeof value})`);
});
// Practical examples
function validateArrayData(data, validators) {
const errors = [];
TAFFY.each(data, function(item, index) {
TAFFY.eachin(validators, function(validator, field) {
if (!validator(item[field])) {
errors.push(`Item ${index}, field '${field}': validation failed`);
}
});
});
return errors;
}
// Summing object values
function sumObjectValues(obj) {
let total = 0;
TAFFY.eachin(obj, function(value, key) {
if (TAFFY.isNumber(value)) {
total += value;
}
});
return total;
}
const sales = { jan: 1000, feb: 1200, mar: 950, apr: 1100 };
console.log(`Total sales: $${sumObjectValues(sales)}`); // Total sales: $4250Utilities for extending TaffyDB functionality with custom methods.
/**
* Add custom methods to the TaffyDB query API
* @param methodName - Name of the new method
* @param fn - Function implementation
*/
TAFFY.extend(methodName: string, fn: function): void;
/**
* Special return value to exit early from iteration functions
*/
TAFFY.EXIT: 'TAFFYEXIT';Usage Examples:
// Add custom query method
TAFFY.extend('findByEmail', function(email) {
return this.filter({ email: { is: email } });
});
// Use custom method
const userDB = TAFFY([
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' }
]);
const alice = userDB().findByEmail('alice@example.com').first();
// Add pagination method
TAFFY.extend('paginate', function(page, pageSize) {
const start = (page - 1) * pageSize + 1;
return this.start(start).limit(pageSize);
});
// Use pagination
const page2Users = userDB().paginate(2, 10).get();
// Add statistics method
TAFFY.extend('stats', function(column) {
const values = this.select(column);
const sum = values.reduce((a, b) => a + b, 0);
return {
count: values.length,
sum: sum,
avg: sum / values.length,
min: Math.min(...values),
max: Math.max(...values)
};
});
// Use statistics
const salaryStats = userDB({ department: 'Engineering' }).stats('salary');
console.log(`Avg salary: $${salaryStats.avg.toFixed(2)}`);
// Using TAFFY.EXIT for early termination
function findFirstMatch(array, predicate) {
let result = null;
TAFFY.each(array, function(item, index) {
if (predicate(item)) {
result = item;
return TAFFY.EXIT; // Stop iteration
}
});
return result;
}Install with Tessl CLI
npx tessl i tessl/npm-taffydb