Created
February 19, 2019 16:20
-
-
Save cmjaimet/e164085fb452da3c4dc24fb666250cf0 to your computer and use it in GitHub Desktop.
Letters (JS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2>Count letters in text</h2> | |
<p>Enter some text and watch the script count each letter in it, and return as a sorted list, most common first.</p> | |
<form> | |
<textarea style="width:90%;height:400px;" id="para"></textarea> | |
</form> | |
<ul id="alpha"></ul> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.getElementById('para').addEventListener( 'keyup', function() { | |
let para = document.getElementById( 'para' ).value; | |
let characters = para.split("").reduce( function( a, x ) { return character_count( a, x ); }, {} ); | |
let sorted = Object.keys( characters ).sort( function( a, b ){ return characters[ b ] - characters[ a ] } ); | |
let dom_out = document.getElementById( 'alpha' ); | |
dom_out.innerHTML = ""; | |
for ( idx in sorted ) { | |
print_character( sorted[ idx ], characters, dom_out ) | |
} | |
} ); | |
function print_character( character, characters, dom_out ) { | |
let asc = character.charCodeAt( 0 ); | |
if ( 96 < asc && 123 > asc ) { | |
// lowercase letter characters are ASCII 97-122 inclusive | |
// console.log( character, characters[ character ] ); | |
let dom_character = format_character( character, characters[ character ] ); | |
dom_out.appendChild( dom_character ); | |
} | |
} | |
function format_character( character, count ) { | |
let dom_output = document.createElement( 'li' ); | |
dom_output.innerHTML = character + ": " + count; | |
return dom_output; | |
} | |
function character_count( a, x ) { | |
x = x.toLowerCase(); | |
if ( ! a[ x[0] ] ) { | |
a[ x[0] ] = 0; | |
} | |
a[ x[0] ] ++; | |
return a; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment