UNPKG

agentsqripts

Version:

Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems

95 lines (86 loc) 2.35 kB
/** * @file Common data processing patterns * @description Utility functions for common data operations */ /** * Filter array by criteria * @param {Array} data - Array to filter * @param {Function} predicate - Filter function * @returns {Array} Filtered array */ function filterBy(data, predicate) { if (!Array.isArray(data)) return []; return data.filter(predicate); } /** * Group array by key function * @param {Array} data - Array to group * @param {Function} keyFn - Function to extract key * @returns {Object} Grouped object */ function groupBy(data, keyFn) { if (!Array.isArray(data)) return {}; return data.reduce((groups, item) => { const key = keyFn(item); groups[key] = groups[key] || []; groups[key].push(item); return groups; }, {}); } /** * Count items by criteria * @param {Array} data - Array to count * @param {Function} keyFn - Function to extract key * @returns {Object} Count object */ function countBy(data, keyFn) { if (!Array.isArray(data)) return {}; return data.reduce((counts, item) => { const key = keyFn(item); counts[key] = (counts[key] || 0) + 1; return counts; }, {}); } /** * Sort array by key function * @param {Array} data - Array to sort * @param {Function} keyFn - Function to extract sort key * @returns {Array} Sorted array */ function sortBy(data, keyFn) { if (!Array.isArray(data)) return []; return [...data].sort((a, b) => { const keyA = keyFn(a); const keyB = keyFn(b); if (keyA < keyB) return -1; if (keyA > keyB) return 1; return 0; }); } /** * Calculate percentage with automatic decimal detection * @param {number} value - Value * @param {number} total - Total * @param {number} decimals - Decimal places (optional) * @returns {number} Percentage */ function calculatePercentage(value, total, decimals) { if (total === 0) return 0; const percentage = (value / total) * 100; // If decimals specified, use that precision if (typeof decimals === 'number') { return parseFloat(percentage.toFixed(decimals)); } // Auto-detect if decimals needed (if result is not a whole number) if (percentage % 1 !== 0) { return parseFloat(percentage.toFixed(2)); } return Math.round(percentage); } module.exports = { filterBy, groupBy, countBy, sortBy, calculatePercentage };