Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Write a function which takes in a string
- // and returns counts of each character in the string.
- function charCount(str) {
- // 1. Make object to return at end.
- var obj = {};
- // 2. Loop over string, for each character
- for (var char of str) {
- // 2.a) If the character is a number/letter AND
- // is a key in object, add 1 to count.
- // 2.b) If the character is a number/letter AND
- // not in object, add it to the object and
- // set value to 1.
- // 2.c) If character is something else (space, period, etc)
- // don't do anything.
- if (isAlphaNumeric(char)) {
- char = char.toLowerCase();
- obj[char] = ++obj[char] || 1;
- }
- }
- // 3. Return object at end.
- return obj;
- }
- function isAlphaNumeric(str) {
- var code;
- for (var i = 0, len = str.length; i < len; i++) {
- code = str.charCodeAt(i);
- if (!(code > 47 && code < 58) && // numeric (0-9)
- !(code > 64 && code < 91) && // upper alpha (A-Z)
- !(code > 96 && code < 123)) { // lower alpha (a-z)
- return false;
- }
- }
- return true;
- }
Add Comment
Please, Sign In to add comment