everyutil
Version:
A comprehensive library of lightweight, reusable utility functions for JavaScript and TypeScript, designed to streamline common programming tasks such as string manipulation, array processing, date handling, and more.
27 lines (26 loc) • 987 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.autoDescribe = void 0;
/**
* Returns human-readable summary of an array.
* @author @dailker
* @param {any[]} array
* @returns {string}
*/
function autoDescribe(array) {
const n = array.length;
const types = Array.from(new Set(array.map(x => typeof x)));
const unique = new Set(array).size;
let mean = '';
if (array.every(x => typeof x === 'number')) {
const avg = array.reduce((a, b) => a + b, 0) / n;
mean = `, mean: ${avg.toFixed(2)}`;
}
let sorted = '';
if (array.every(x => typeof x === 'number' || typeof x === 'string')) {
const asc = array.slice().sort((a, b) => (a > b ? 1 : -1));
sorted = JSON.stringify(array) === JSON.stringify(asc) ? ', sorted ascending' : '';
}
return `Array of ${n} ${types.join('/')}s${mean}, ${unique} unique values${sorted}`;
}
exports.autoDescribe = autoDescribe;