본문 바로가기
알고리즘/Codewars

[Codewars] Count characters in your string (6 kyu) / JavaScript

by fluss 2023. 2. 2.

https://www.codewars.com/kata/52efefcbcdf57161d4000091

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}.

What if the string is empty? Then the result should be empty object literal, {}.

 

코드

function count (string) {
  let str = string.split('');
  let map = new Map();
  for(let i = 0; i < str.length; i++){
    if(map.has(str[i])){
      map.set(str[i], map.get(str[i]) + 1);
    } else{
      map.set(str[i], 1);
    }
  }
  return Object.fromEntries(map);
}

 

다른 사람의 좋았던 풀이

function count (string) {  
  var count = {};
  string.split('').forEach(function(s) {
     count[s] ? count[s]++ : count[s] = 1;
  });
  return count;
}

 

댓글