UNPKG

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.

26 lines (25 loc) 701 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stringEntropy = void 0; /** * Returns the Shannon entropy of a string. * * Useful for detecting randomness, passwords, or encoded data. * * @author @dailker * @param {string} str - The input string. * @returns {number} The Shannon entropy. */ function stringEntropy(str) { const freq = new Map(); for (const ch of str) freq.set(ch, (freq.get(ch) ?? 0) + 1); const n = str.length; let ent = 0; for (const count of freq.values()) { const p = count / n; ent -= p * Math.log2(p); } return ent; } exports.stringEntropy = stringEntropy;