Vera Perrone
Vera Perrone

Reputation: 369

Is there a way to write this small piece of code in a more elegant, optimized way? (ES6)

I have been trying to teach myself ES6 for a short while now. Here is a small example of stuff that I learned, like let, const and => functions. Is there a more elegant or shorter way to write this? Maybe replace for loop with forEach? Any tips and help are welcome.

'use strict';
const countChar = (string, ch) => {
    let counted = 0;
    for (let i = 0; i < string.length; i++) {
        if (string.charAt(i) === ch) {
            counted += 1;
        }
    }
    return counted;
};

const countBs = string => countChar(string, 'B');

console.log(countBs('BBC'));
console.log(countChar('kakkerlak', 'k'));

Upvotes: 1

Views: 77

Answers (4)

ray
ray

Reputation: 27275

Have you considered regular expressions?

alert('kakkerlak'.match(/k/g).length)

Upvotes: 3

adeneo
adeneo

Reputation: 318312

Here's another way to shorten it

'use strict';
const countChar = (string, ch) => string.split(ch).length - 1;
const countBs = string => countChar(string, 'B');

console.log(countBs('BBC'));
console.log(countChar('kakkerlak', 'k'));

Upvotes: 4

TimoStaudinger
TimoStaudinger

Reputation: 42490

Not necessarily related to ES6, but a more functional approach, e.g. using filter() seems nice here:

const countChar = (string, needle) =>
  string.split('')
    .filter(char => char === needle)
    .length;

const countBs = string => countChar(string, 'B');

console.log(countBs('BBC'));
console.log(countChar('kakkerlak', 'k'));

Upvotes: 2

Mike Cluck
Mike Cluck

Reputation: 32511

Elegance is in the eye of the beholder but here's a way to reduce it further by using reduce:

'use strict';

const countChar = (string, ch) => 
  string.split('').reduce((sum, c) => sum + (c === ch), 0);

const countBs = string => countChar(string, 'B');

console.log(countBs('BBC'));
console.log(countChar('kakkerlak', 'k'));

It works by converting the string into an array of characters then summing up the number of characters in that array which match ch. I also (ab)use the fact that true converts to 1 and false converts to 0 so adding c === ch to the running sum will add 1 if it matches and 0 if it doesn't.

Upvotes: 1

Related Questions