섹션 4: 문제 해결 접근법

선정·2023년 10월 22일
0
  1. UnderStand the Problem
  2. Explore Concrete Examples
  3. Break It Down
  4. Solve/Simplify
  5. Look Back and Refactor

regular expression (1)

function charCount(str) {
  const obj = {};
  for(let char of str) {
    char = char.toLowerCase();
    if(/[a-z0-9]/.test(char)) {
      if(obj[char] > 0) {
        obj[char]++;
      } else {
        obj[char] = 1;
      }
    }
  }
  return obj;
}

regular expression (2) - simpler version

function charCount(str) {
  const obj = {};
  for(let char of str) {
    char = char.toLowerCase();
    if(/[a-z0-9]/.test(char)) {
      obj[char] = ++obj[char] || 1;
    }
  }
  return obj;
}

charAtCode() - instead of regular expression

function charCount(str) {
  const obj = {};
  for(let char of str) {
    if(isAlphaNumeirc(char)) {
      char = char.toLowerCase();
      obj[char] = ++obj[char] || 1;
    }
  }
  return obj;
}

function isAlphaNumeirc(char) {
  let code = char.charCodeAt(0);
  if(!(code>47 && code<58) && !(code>64 && code<91) && !(code>94 && code<123)) {
    return false;
  }
  return true;
}
profile
starter

0개의 댓글