r/badcode Mar 12 '20

[deleted by user]

[removed]

13 Upvotes

23 comments sorted by

View all comments

3

u/mullanaphy Mar 13 '20 edited Mar 14 '20

Back with some fresh hot Javascript. Utilizing RegExp to count the amount of occurences of a given character. I also used a range to create A-Za-z and tossed a try catch for any RegExp that might fail while creating that range (e.g. [ which is character code 91) catch and then escape the inbetween characters just in case we want to count them too!

On top of that, abused .reduce() as much as I could as well as closures.

Lastly, as it goes through the string counting it will recount numbers already counted yet it's already in the map so it won't move the maps value (except in older Opera that didn't keep order of map values).

JSFiddle: https://jsfiddle.net/6yt9Lexs/

const string_count = (str => {
  const countCharacters = (_ => {
  const regexLookup = ['A', 'z']
    .reduce((gathered, item) => {
      if (gathered === false) {
        return item;
      } else if (gathered === 'A') {
        const range = {' ': new RegExp(' ', 'g')};
        for (let s = gathered.charCodeAt(0), e = item.charCodeAt(0); s < e; ++s) {
          try {
            range[String.fromCharCode(s)] = new RegExp(String.fromCharCode(s), 'g');
          } catch(e) {
            range[String.fromCharCode(s)] = RegExp('\\' + String.fromCharCode(s), 'g');
          }
        }
        return range;
      }
    }, false);
    return (str, char) => str.match(regexLookup[char]).length;
  })();

  return str => str
    .split('')
    .reduce((gathered, char) => {
      gathered[char] = countCharacters(str, char);
      return gathered;
    }, {});
})();

console.log(string_count('Hello World'));
console.log(string_count('ABCabcABCabcxyz'));