Skip to content

Instantly share code, notes, and snippets.

@jaysonmulwa
Forked from radekk/entropy.js
Created October 28, 2022 20:06
Show Gist options
  • Save jaysonmulwa/28bc8f78cab39aae26b045f99e51969d to your computer and use it in GitHub Desktop.
Save jaysonmulwa/28bc8f78cab39aae26b045f99e51969d to your computer and use it in GitHub Desktop.
Calculating Shannon's entropy with JavaScript
/**
* Calculate Shannon's entropy for a string
*/
module.exports = (str) => {
const set = {};
str.split('').forEach(
c => (set[c] ? set[c]++ : (set[c] = 1))
);
return Object.keys(set).reduce((acc, c) => {
const p = set[c] / str.length;
return acc - (p * (Math.log(p) / Math.log(2)));
}, 0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment