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.
23 lines (22 loc) • 577 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.entropy = void 0;
/**
* Returns the Shannon entropy of the array.
* @author @dailker
* @param {any[]} array
* @returns {number}
*/
function entropy(array) {
const freq = new Map();
for (const item of array)
freq.set(item, (freq.get(item) ?? 0) + 1);
const n = array.length;
let ent = 0;
for (const count of freq.values()) {
const p = count / n;
ent -= p * Math.log2(p);
}
return ent;
}
exports.entropy = entropy;