agentsqripts
Version:
Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems
45 lines (42 loc) • 1.98 kB
JavaScript
/**
* @file Array sorting utility for property-based and custom ordering operations
* @description Single responsibility: Sort array items by specified properties or custom comparison functions
*
* This utility provides flexible array sorting capabilities that support both property-based
* sorting and custom comparison functions. It enables consistent data organization across
* the AgentSqripts platform while maintaining type safety and performance optimization
* for large datasets and complex sorting requirements.
*
* Design rationale:
* - Dual interface supports both simple property sorting and complex custom comparisons
* - Type-agnostic implementation handles diverse data structures and property types
* - Stable sorting algorithm maintains consistent ordering for equal elements
* - Performance-optimized implementation scales efficiently with large arrays
* - Immutable approach preserves original array while creating sorted results
*
* Sorting capabilities:
* - Property-based sorting using string property names for simple cases
* - Custom comparison function support for complex ordering requirements
* - Multi-level sorting through function composition and chaining
* - Type-safe sorting that maintains array type consistency throughout operations
* - Null-safe property access with graceful handling of missing properties
*/
/**
* Sort items by property
* @param {Array} items - Items to sort
* @param {string|Function} sortKey - Sort key or function
* @param {boolean} descending - Sort in descending order
* @returns {Array} Sorted items
*/
function sortBy(items, sortKey, descending = false) {
const getValue = typeof sortKey === 'string'
? (item) => item[sortKey]
: sortKey;
return [...items].sort((a, b) => {
const aVal = getValue(a);
const bVal = getValue(b);
const result = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
return descending ? -result : result;
});
}
module.exports = sortBy;