Skip to content

Instantly share code, notes, and snippets.

@findzen
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save findzen/ec259168759ca29bdfc9 to your computer and use it in GitHub Desktop.
Save findzen/ec259168759ca29bdfc9 to your computer and use it in GitHub Desktop.
;(function(window, document, undefined) {
'use strict';
// ensure only one instance is running at a time
if (window._fz_wordcloud) return;
window._fz_wordcloud = true;
var MAX_WORDS = 50;
var BASE_FONT_SIZE = 12;
var words = document.body.innerText.toLowerCase()
.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()?]/g, '').split(/[\s\/]+/g).sort();
var counts = {};
var result = [];
words.forEach(function(val) {
if (val.length < 4) return;
counts[val] = counts[val] ? counts[val] + 1 : 1;
});
for (var word in counts) {
result.push({ word: word, count: counts[word] });
}
function sortBy(array, property) {
return array.sort(function(a, b) {
if (a[property] < b[property]) return -1;
if (a[property] > b[property]) return 1;
return 0; // a[property] === b[property]
});
}
// sort by count, return most used words, then sort alphabetically
result = sortBy(sortBy(result, 'count').slice(-MAX_WORDS), 'word');
var container = document.createElement('div');
var p = document.createElement('p');
container.style.background = '#fff';
container.style.position = 'fixed';
container.style.top = 0;
container.style.right = 0;
container.style.width = '100%';
container.style.height = '100%';
container.style.zIndex = Number.MAX_SAFE_INTEGER || 9007199254740991;
p.style.fontColor = '#ccc';
p.style.padding = '50px';
p.style.width = '50%';
p.style.textAlign = 'justify';
p.style.margin = '0 auto';
container.appendChild(p);
// display in div with font-size according to frequency
result.forEach(function(obj) {
var space = document.createTextNode(' ');
var span = document.createElement('span');
span.innerText = obj.word;
span.style.fontSize = BASE_FONT_SIZE + obj.count + 'px';
p.appendChild(space);
p.appendChild(span);
});
document.body.appendChild(container);
// destroy the container on click
container.addEventListener('click', function(e) {
document.body.removeChild(container);
container.removeEventListener('click');
window._fz_wordcloud = undefined;
});
})(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment