Skip to content

Instantly share code, notes, and snippets.

@eagle26
Forked from jabney/entropy.js
Last active February 7, 2019 17:01
Show Gist options
  • Save eagle26/200da994195496930aa6c1baf81c20c0 to your computer and use it in GitHub Desktop.
Save eagle26/200da994195496930aa6c1baf81c20c0 to your computer and use it in GitHub Desktop.
Javascript implementation of a Shannon entropy calculation in bits per symbol
// entropy.js MIT License © 2014 James Abney http://github.com/jabney
// Calculate the Shannon entropy of a string in bits per symbol.
(function(shannon) {
'use strict';
// Create a dictionary of character frequencies and iterate over it.
function process(s, evaluator) {
var h = Object.create(null), k;
s.split('').forEach(function(c) {
h[c] && h[c]++ || (h[c] = 1); });
if (evaluator) for (k in h) evaluator(k, h[k]);
return h;
};
// Measure the entropy of a string in bits per symbol.
shannon.entropy = function(s) {
var sum = 0,len = s.length;
process(s, function(k, f) {
var p = f/len;
sum -= p * Math.log(p) / Math.log(2);
});
return sum;
};
// Measure the entropy of a string in total bits.
shannon.bits = function(s) {
return Math.ceil(shannon.entropy(s)) * s.length;
};
// Get entropy level
shannon.level = function (s) {
var H = shannon.bits(s);
var l = 'dummy'; //Text level
if(H < 35){
l = 'week';
} else if (H < 55){
l = 'medium';
} else {
l = 'strong';
}
return l;
};
// Log the entropy of a string to the console.
shannon.log = function(s) {
console.log('Entropy of "' + s + '" in bits per symbol:', shannon.bits(s));
};
})(window.shannon = window.shannon || Object.create(null));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment