Guest User

Untitled

a guest
Oct 15th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. // Write a function which takes in a string
  2. // and returns counts of each character in the string.
  3.  
  4. function charCount(str) {
  5. // 1. Make object to return at end.
  6. var obj = {};
  7. // 2. Loop over string, for each character
  8. for (var char of str) {
  9. // 2.a) If the character is a number/letter AND
  10. // is a key in object, add 1 to count.
  11. // 2.b) If the character is a number/letter AND
  12. // not in object, add it to the object and
  13. // set value to 1.
  14. // 2.c) If character is something else (space, period, etc)
  15. // don't do anything.
  16. if (isAlphaNumeric(char)) {
  17. char = char.toLowerCase();
  18. obj[char] = ++obj[char] || 1;
  19. }
  20. }
  21. // 3. Return object at end.
  22. return obj;
  23. }
  24.  
  25. function isAlphaNumeric(str) {
  26. var code;
  27.  
  28. for (var i = 0, len = str.length; i < len; i++) {
  29. code = str.charCodeAt(i);
  30. if (!(code > 47 && code < 58) && // numeric (0-9)
  31. !(code > 64 && code < 91) && // upper alpha (A-Z)
  32. !(code > 96 && code < 123)) { // lower alpha (a-z)
  33. return false;
  34. }
  35. }
  36. return true;
  37. }
Add Comment
Please, Sign In to add comment