Skip to content

Instantly share code, notes, and snippets.

@clupasq
Created February 20, 2015 22:14
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 clupasq/fd00f20ba537408d1a0b to your computer and use it in GitHub Desktop.
Save clupasq/fd00f20ba537408d1a0b to your computer and use it in GitHub Desktop.
Programming Puzzles and Code Golf character counter for answers
/* stolen from http://stackoverflow.com/a/5515960/390819 */
function lengthInUtf8Bytes(str) {
/* Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence. */
var m = encodeURIComponent(str).match(/%[89ABab]/g);
return str.length + (m ? m.length : 0);
}
var answers = document.querySelectorAll('div.answer');
var codeBoxes = Array.prototype.map.call(answers, function(a){
return a.querySelector('pre');
}).filter(function (x) { return x; });
codeBoxes.forEach(function(c){
var length = lengthInUtf8Bytes(c.textContent.replace(/\n*$/, ''));
var countDiv = document.createElement('div');
countDiv.style.color = 'rgb(239, 110, 31)';
countDiv.innerHTML = 'Byte count: <strong>' + length + '</strong>';
c.parentNode.insertBefore(countDiv, c);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment